java check date string is legal

1. Use SimpleDateFormat (with pits)

    private static boolean isValidDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        try {
            format.setLenient(false);
            return format.parse(str)==null?false:true;
        } catch (Exception e) {
            return false;
        }
    }

The above method cannot be verified. For example, the date string is: 202001011, 202001010, the length has exceeded 8 digits, but the verification result is true;

 

2. Use date column verification in java8

    private static boolean isValid(String dateStr){
        String format = "yyyyMMdd";
        DateTimeFormatter ldt = DateTimeFormatter.ofPattern(format.replace("y", "u")).withResolverStyle(ResolverStyle.STRICT);
        try {
            return LocalDate.parse(dateStr, ldt)==null?false:true;
        } catch (Exception e) {
           return false;
        }
    }

 

Guess you like

Origin blog.csdn.net/qq_36807862/article/details/108677156