带有可选部分的Java 8 DateTimeFormatter [英] Java 8 DateTimeFormatter with optional part

查看:117
本文介绍了带有可选部分的Java 8 DateTimeFormatter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串代表日期(有或没有时间),如 13/12/2017 13/12/2017 15:39 :51

I have a String representing a date (with or without time) like 13/12/2017 or 13/12/2017 15:39:51

所以我正在尝试将java 8 DateTimeFormatter与可选部分一起使用。

So i'm trying to use java 8 DateTimeFormatter with optional part.

该代码有效

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

但我不明白为什么那个没有

But I don't understand why that one does not

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"));

它不能用于相同的异常。

it does not work with the same exception.

推荐答案

使用 parseBest



使用可选组件时,应使用 parseBest 进行解析。您的应用程序可能只使用解析,但这只是运气(因为您只解析完整的输入,而不是部分输入)。使用 parseBest ,您可以正确处理各种 TemporalAccessor ,这是使用可选项的全部原因。

Use parseBest

When you use an optional component, you should parse using parseBest. Your application may be working using only parse, but then it's only by luck (because you're only parsing full inputs, not partial ones). With parseBest, you can properly handle various TemporalAccessor, which is the whole reason to use optional.

返回 TemporalAccessor 的决定相当简单: parseBest 将尝试按参数顺序匹配每个 TemporalQuery 。当任何匹配时,该方法返回该匹配。因此,请确保从最精确到最精确。此外,如果没有匹配,则会抛出异常。

The decision of which TemporalAccessor is returned is rather simple: parseBest will try to match each TemporalQuery in order of argument. When any matches, the method returns that one. So make sure to go from most precise to less precise. Also, if none were matched, an exception will be thrown.

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

这篇关于带有可选部分的Java 8 DateTimeFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆