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

时间字符串格式校验

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

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

此方法可以严格校验 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);
}

这是因为在 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;
}
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;
}

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值