Java validate date in yyyyMMddHHmmss

前端 未结 1 1817
Happy的楠姐
Happy的楠姐 2021-01-29 09:58

i want to validate the given date format as yyyyMMddHHmmss in java.

Conditions:

  1. It should meet the format yyyyMMddHHmmss.

  2. It should val

1条回答
  •  执念已碎
    2021-01-29 10:57

    Use two other dates, three hours ahead and three hours behind, for comparison. Then make sure the date that you are parsing is between those two boundaries using compareTo().

    You really shouldn't put numbers in your class names, but that's a style issue that's irrelevant to the answer.

    public class SO31132861 {
    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        df.setLenient(false);
    
        System.out.println(tryParse(df, "20160630231110"));
        System.out.println(tryParse(df, "20150228231100"));
        System.out.println(tryParse(df, "20160229231100"));
    
        System.out.println(tryParse(df, "21000229231100")); // 29th Feb on non-leap year 2100
        System.out.println(tryParse(df, "20160631231110")); // 31st Jun invalid day
        System.out.println(tryParse(df, "20160229231160")); // Second > 59
        System.out.println(tryParse(df, "20150229231100")); // 29th Feb on non-leap year 2015
        System.out.println(tryParse(df, "20150228241100")); // Hour > 23
    
    }
    
    private static Boolean tryParse(DateFormat df, String s) {
        Boolean valid=false;
        try {
            Date threeHoursBefore = new Date();
            threeHoursBefore.setTime(System.currentTimeMillis() - (3*60*60*1000));
    
            Date threeHoursAfter = new Date();
            threeHoursAfter.setTime(System.currentTimeMillis() + (3*60*60*1000));
    
            Date dateToParse= df.parse(s);
    
            valid=dateToParse.compareTo(threeHoursBefore) > 0 && dateToParse.compareTo(threeHoursAfter) < 0;
        } catch (ParseException e) {
             valid=false;
        }
        return valid;
    }
    }
    

    0 讨论(0)
提交回复
热议问题