比较好的日期验证方法(2012.08.02)

今天工作碰到了一个日期验证的东西,写了个方法进行日期的验证,给定的String格式为“yyyy-MM-dd”,这个可以自行更改。

public class DateTools {

    public static String PATTERN_DATE_DAY = "yyyy-MM-dd";
    public static String PATTERN_DATE_MONTH = "yyyy-MM";
    public static String PATTERN_DATE_YEAR = "yyyy";
    private static String REGEX_DAY = "^\\d{4}-\\d{1,2}-\\d{1,2}$";
    private static String REGEX_MONTH = "^\\d{4}-\\d{1,2}$";
    private static String REGEX_YEAR = "^\\d{4}$";

    public static Calendar parseStringToDate(String startDate) {
        boolean matchesYear = Pattern.matches(REGEX_YEAR, startDate);
        boolean matchesMonth = Pattern.matches(REGEX_MONTH, startDate);
        boolean matchesDay = Pattern.matches(REGEX_DAY, startDate);

        String dateString = PATTERN_DATE_DAY;
        if (matchesYear) {
            dateString = PATTERN_DATE_YEAR;
        } else if (matchesMonth) {
            dateString = PATTERN_DATE_MONTH;
        } else if (matchesDay) {
            dateString = PATTERN_DATE_DAY;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat(dateString);
        try {
            Date date = dateFormat.parse(startDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            if (matchesMonth) {
                String month = "" + Integer.parseInt(startDate.substring(startDate.indexOf("-") + 1 ));
                String mm = String.valueOf(calendar.get(Calendar.MONTH) + 1);
                if (!month.equals(mm)) {
                    return null;
                }
            }
            if (matchesDay) {
                String year = "" + Integer.parseInt(startDate.substring(0, startDate.indexOf("-")));
                String month = "" + Integer.parseInt(startDate.substring(startDate.indexOf("-") + 1, startDate.lastIndexOf("-")));
                String day = "" + Integer.parseInt(startDate.substring(startDate.lastIndexOf("-") + 1));
                String yy = String.valueOf(calendar.get(Calendar.YEAR));
                String mm = String.valueOf(calendar.get(Calendar.MONTH) + 1);
                String dd = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
                if (!year.equals(yy) || !month.equals(mm) || !day.equals(dd)) {
                    return null;
                }
            }
            return calendar;
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return null;
    }

}

你可能感兴趣的:(Date,String,calendar,null,Class,regex)