我需要做什么 : 我需要将一个LocalDateTime对象传递给构造函数,并且我有一个字符串,其值为“18:14:00”。
我的问题 : 如何将字符串转换为LocalDateTime?
我做了什么 : 经过一些研究,我把它放了但是它不起作用:
LocalDateTime.parse("18:14:00", DateTimeFormatter.ofPattern("HH:mm:ss"));
java.time.format.DateTimeParseException:无法解析文本'18:14:00':无法从TemporalAccessor获取LocalDateTime:{},ISO解析为java.time.format.Parsed类型的18:14
“无法获取LocalDateTime”异常是因为解析后的文本只有时间值,没有日期值,因此无法构造Local Date Time对象。
改为使用LocalTime
:
LocalTime time = LocalTime.parse("18:14:00");
System.out.println(dateTime); // Prints: 18:14
"HH:mm:ss"
模式是LocalTime
的默认模式,因此无需指定它(请参阅:DateTimeFormatter.ISO_LOCAL_TIME
)。
如果你想/需要一个LocalDateTime
对象,解析类似于SimpleDateFormat
的做法,即默认1970年1月1日,那么你需要明确指定默认日期值:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.parseDefaulting(ChronoField.EPOCH_DAY, 0)
.toFormatter();
LocalDateTime dateTime = LocalDateTime.parse("18:14:00", fmt);
System.out.println(dateTime); // Prints: 1970-01-01T18:14
为了比较,这相当于旧的SimpleDateFormat
结果:
Date date = new SimpleDateFormat("HH:mm:ss").parse("18:14:00");
System.out.println(date); // Prints: Thu Jan 01 18:14:00 EST 1970
您有时间组件,而不是日期组件。所以你能做的最好(你拥有的)是使用LocalTime
(而不是LocalDateTime
)。喜欢,
LocalTime lt = LocalTime.parse("18:14:00", DateTimeFormatter.ofPattern("HH:mm:ss"));