java 校验日期字符串是否合法

1.使用SimpleDateFormat(有坑)

    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;
        }
    }

以上方法无法校验例如日期字符串为:202001011,202001010,长度已经超过8位,但校验结果为true;

2.使用 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;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_36807862/article/details/108677156
今日推荐