当前位置:   article > 正文

Java8 时间字符串校验是否为对应的日期格式_java判断日期字符串格式

java判断日期字符串格式

时间字符串格式校验

严格模式下校验日期字符串

public static boolean isDateStrict(String dateStr, String pattern) {
    try {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyyyMMdd")
            .parseDefaulting(ChronoField.ERA, 1)
            .toFormatter()
            .withChronology(IsoChronology.INSTANCE)
            .withResolverStyle(ResolverStyle.STRICT);
        LocalDate.parse(dateStr, formatter);
    } catch (Exception e) {
        log.error("时间格式不正确:{}", e.getMessage());
        return false;
    }
    return true;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

此方法可以严格校验 yyyyMMdd 的日期格式,或直接使用 uuuuMMdd 的形式转化:

private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("uuuuMMdd ")
                                    .withChronology(IsoChronology.INSTANCE)
                                    .withResolverStyle(STRICT);
public static LocalDate parse(String dateStr) {
    return LocalDate.parse(dateStr, FORMAT);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这是因为在 Java 8 的新日期 API 下,yyyy 表示公元纪年(year-era),这种格式在解析日期时会检查公元位(G),不存在时会报错;而 uuuu 表示和公元没有关系的年。上面例子中使用 parseDefaulting(ChronoField.ERA, 1) 设置一个默认的公元纪年位,表示公元后,就和我们正常的日期保持一致。

严格模式下使用yyyy不指定纪元的报错:

java.time.format.DateTimeParseException: Text ‘19820228’ could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=2, DayOfMonth=28, YearOfEra=1982},ISO of type java.time.format.Parse

当然如果你使用非严格模式,yyyy 和 uuuu 在使用上没有区别。

如果使用非严格模式的 DateTimeFormatter 可能并不会真正的检查出日期字符串的错误,比如 20230230,转日期类型并不会报错,会自动转成一个正确的日期 20230228;

而使用 SimpleDateFormmat 也会有一些问题,比如 2023052,会转成 20230502。

public static boolean isDateSimple(String dateStr, String pattern) {
    try {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        format.setLenient(false);
        format.parse(dateStr);
    } catch (Exception e) {
        log.error("时间格式不正确:{}", e.getMessage());
        return false;
    }
    return true;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
public static boolean isDateFormatter(String dateStr, String pattern) {
    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDate.parse(dateStr, formatter);
    } catch (Exception e) {
        log.error("时间格式不正确:{}", e.getMessage());
        return false;
    }
    return true;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

参考:https://stackoverflow.com/questions/26393594/using-new-java-8-datetimeformatter-to-do-strict-date-parsing

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52126
推荐阅读
相关标签
  

闽ICP备14008679号