Java Date Value Check isDate(String input)

Here you can find the source of isDate(String input)

Description

is Date

License

Apache License

Declaration

public static boolean isDate(String input) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    public static boolean isDate(String input) {
        if (input == null) {
            return false;
        }/* ww w. j a v  a 2  s .  c om*/

        try {
            ymdOrYmdhms2Date(input);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    /**
     * Ymd or ymdhms2 date.
     * 
     * @param str
     *            the str
     * 
     * @return the date
     * 
     * @throws ParseException
     *             the parse exception
     */
    private static Date ymdOrYmdhms2Date(String str) throws ParseException {
        if (str == null)
            return null;
        if (str.length() != 10 && str.length() != 19 && str.length() != 23) {
            throw new ParseException("error date:" + str, 0);
        }

        char[] strs = str.toCharArray();
        Calendar cal = null;
        try {
            int year = parseInt(strs, 0, 4);
            int month = parseInt(strs, 5, 7) - 1;
            int date = parseInt(strs, 8, 10);
            if (strs.length >= 19) {
                int hrs = parseInt(strs, 11, 13);
                int min = parseInt(strs, 14, 16);
                int sec = parseInt(strs, 17, 19);
                cal = new GregorianCalendar(year, month, date, hrs, min, sec);
                if (strs.length == 23) {
                    int sss = parseInt(strs, 20, 23);
                    cal.set(Calendar.MILLISECOND, sss);
                }
            } else {
                cal = new GregorianCalendar(year, month, date);
            }
            return cal.getTime();
        } catch (ParseException e) {
            throw e;
        }
    }

    private static int parseInt(char[] strs, int beginindex, int endindex) throws ParseException {
        int result = 0;
        int b = 1;
        for (int i = endindex - 1; i >= beginindex; i--) {
            if (strs[i] < 48 || strs[i] > 57) {
                throw new ParseException("Parse error,can't parse char to int . ", 0);
            }
            result = result + (strs[i] - 48) * b;
            b *= 10;
        }
        return result;
    }
}

Related

  1. isDate(String date)
  2. isDate(String dateStr, String dateFormat)
  3. isDate(String dateString)
  4. isDate(String dttm, String format)
  5. isDate(String input)
  6. isDate(String pattern, String text)
  7. isDate(String s)
  8. isDate(String str)
  9. isDate(String str)