//pattern使用中,小时使用小写的hh程序能会报错 LocalDateTime now = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String format3 = now.format(dateTimeFormatter3); System.out.println(format3); System.out.println(LocalDateTime.parse(format3, dateTimeFormatter3));
//pattern使用中,小时使用大写的HH程序能正常解析 LocalDateTime now = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String format3 = now.format(dateTimeFormatter3); System.out.println(format3); System.out.println(LocalDateTime.parse(format3, dateTimeFormatter3));
疑似,hh和HH兼容性未做好。(jdk1.8)
有的小伙伴说了,那么报错原因是什么?
DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //使用小写hh会报错
String format3 = now.format(dateTimeFormatter3);
System.out.println(format3);
System.out.println(LocalDateTime.parse(format3, dateTimeFormatter3));
追踪LocalDateTime.parse报错原因
public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, LocalDateTime::from);
}
追踪到是因为LocalDateTime::from的方法导致报错的。我们进入LocalDateTime类找到from方法。
public static LocalDateTime from(TemporalAccessor temporal) {
if (temporal instanceof LocalDateTime) {
return (LocalDateTime) temporal;
} else if (temporal instanceof ZonedDateTime) {
return ((ZonedDateTime) temporal).toLocalDateTime();
} else if (temporal instanceof OffsetDateTime) {
return ((OffsetDateTime) temporal).toLocalDateTime();
}
try {
LocalDate date = LocalDate.from(temporal);
LocalTime time = LocalTime.from(temporal);
return new LocalDateTime(date, time);
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to obtain LocalDateTime from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName(), ex);
}
}
继续追踪是因为这里LocalTime.from(temporal)报的错。我们继续跟进
public static LocalTime from(TemporalAccessor temporal) {
Objects.requireNonNull(temporal, "temporal");
LocalTime time = temporal.query(TemporalQueries.localTime());
if (time == null) {
throw new DateTimeException("Unable to obtain LocalTime from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName());
}
return time;
}
结果是在这个api中 temporal.query取不到值,此时localTime类型的time变量为空,所以直接业务抛出异常报错了。
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("hh:mm:ss");
String format2 = now.format(dateTimeFormatter2);
System.out.println(format2);
System.out.println(LocalTime.parse(format2));
然而,仍然是hh:mm:ss,单独出现,在没有加年月日的情况下,用LocalTime进行解析,就能解析成功。
我纠结的是这个。