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不指定纪元的报错:
当然如果你使用非严格模式,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
因篇幅问题不能全部显示,请点此查看更多更全内容