我有一个代表日期(有或没有时间)的字符串,例如13/12/2017
or 13/12/2017 15:39:51
所以我尝试将 java 8 DateTimeFormatter 与可选部分一起使用。
该代码有效
LocalDateTime localDateTime = LocalDateTime.parse("13/12/2017 15:39:51",DateTimeFormatter.ofPattern("dd/MM/yyyy[ HH:mm:ss]"));
System.out.println(localDateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
System.out.println(localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
13/12/2017
15:39:51
但我不明白为什么那个人不
LocalDateTime localDateTime = LocalDateTime.parse("13/12/2017",DateTimeFormatter.ofPattern("dd/MM/yyyy[ HH:mm:ss]"));
给我
Exception in thread "main" java.time.format.DateTimeParseException: Text '13/12/2017' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2017-12-13 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
...
甚至与
LocalDateTime localDateTime = LocalDateTime.parse("13/12/2017",DateTimeFormatter.ofPattern("dd/MM/yyyy"));
它不适用于相同的异常。
Use parseBest
当您使用可选组件时,您应该使用parseBest
。您的应用程序可能仅使用parse
,但这只是运气(因为您只解析完整的输入,而不是部分输入)。和parseBest
,可以妥善处理各种TemporalAccessor
,这就是使用可选的全部原因。
其中的决定TemporalAccessor
返回的结果相当简单:parseBest
将尝试匹配每个TemporalQuery
按照论证的顺序。当有任何匹配时,该方法将返回该匹配。因此,请确保从最精确到不太精确。另外,如果没有匹配,则会抛出异常。
LocalDateTime dateTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy[ HH:mm:ss]");
TemporalAccessor temporalAccessor = formatter.parseBest("13/12/2017", LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof LocalDateTime) {
dateTime = (LocalDateTime)temporalAccessor;
} else {
dateTime = ((LocalDate)temporalAccessor).atStartOfDay();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)