无法使用 Java 8 中的 DateTimeFormatter 和 ZonedDateTime 从 TemporalAccessor 获取 ZonedDateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23596530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to obtain ZonedDateTime from TemporalAccessor using DateTimeFormatter and ZonedDateTime in Java 8
提问by Faliorn
I recently moved to Java 8 to, hopefully, deal with local and zoned times more easily.
我最近转向 Java 8,希望能够更轻松地处理本地和分区时间。
However, I'm facing an, in my opinion, simple problem when parsing a simple date.
但是,在我看来,解析简单日期时遇到了一个简单的问题。
public static ZonedDateTime convertirAFecha(String fecha) throws Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
ConstantesFechas.FORMATO_DIA).withZone(
obtenerZonaHorariaServidor());
ZonedDateTime resultado = ZonedDateTime.parse(fecha, formatter);
return resultado;
}
In my case:
就我而言:
- fecha is '15/06/2014'
- ConstantesFechas.FORMATO_DIA is 'dd/MM/yyyy'
- obtenerZonaHorariaServidor returns ZoneId.systemDefault()
- fecha 是 '15/06/2014'
- ConstantesFechas.FORMATO_DIA 是 'dd/MM/yyyy'
- obtenerZonaHorariaServidor 返回 ZoneId.systemDefault()
So, this is a simple example. However, the parse throws this exception:
所以,这是一个简单的例子。但是,解析会引发此异常:
java.time.format.DateTimeParseException: Text '15/06/2014' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2014-06-15 of type java.time.format.Parsed
java.time.format.DateTimeParseException:无法解析文本“15/06/2014”:无法从 TemporalAccessor 获取 ZonedDateTime:{},ISO 解析为 java.time.format.Parsed 类型的 2014-06-15
Any tips? I've been trying different combinations of parsing and using TemporalAccesor, but without any luck so far.
有小费吗?我一直在尝试解析和使用 TemporalAccesor 的不同组合,但到目前为止没有任何运气。
Best regards
此致
采纳答案by assylias
This does not work because your input (and your Formatter) do not have time zone information. A simple way is to parse your date as a LocalDate
first (without time or time zone information) then create a ZonedDateTime
:
这不起作用,因为您的输入(和您的格式化程序)没有时区信息。一个简单的方法是将您的日期解析为LocalDate
第一个(没有时间或时区信息),然后创建一个ZonedDateTime
:
public static ZonedDateTime convertirAFecha(String fecha) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = LocalDate.parse(fecha, formatter);
ZonedDateTime resultado = date.atStartOfDay(ZoneId.systemDefault());
return resultado;
}
回答by Meno Hochschild
This is a bug, see JDK-bug-log. According to that information the problem was solved for Java 9 and Java 8u20. Try to download the latest Java 8 - version. Today on 2014-05-12: There is an early access release 8u20available.
这是一个错误,请参阅JDK-bug-log。根据该信息,该问题已在 Java 9 和 Java 8u20 中解决。尝试下载最新的 Java 8 - 版本。2014 年 5月 12 日的今天:有一个早期访问版本 8u20可用。
UPDATE:
更新:
Personally I think, since you only have and expect "dd/MM/yyyy" as pattern you should use LocalDate
as your primary type as @assylias has already proposed. Regarding your context, it is almost sure a design failure to use ZonedDateTime
. What do you want to do with objects of this type? I can only think of specialized timezone calculations as use-case. And you cannot even directly store these ZonedDateTime
-objects in a database, so this type is far less useful than many people believe.
我个人认为,由于您只有并期望“dd/MM/yyyy”作为模式,您应该LocalDate
像@assylias 已经提出的那样将其用作主要类型。关于您的上下文,几乎可以肯定使用ZonedDateTime
. 你想用这种类型的对象做什么?我只能将专门的时区计算视为用例。而且您甚至无法直接将这些ZonedDateTime
-objects存储在数据库中,因此这种类型远没有许多人认为的那么有用。
What I described as your use-case problem is indeed a new aspect introduced with Java-8 compared with the old GregorianCalendar
-class (which is an all-in-one-type). Users have to start thinking about choosing the proper temporal type for their problems and use-cases.
我所描述的用例问题确实是 Java-8 引入的一个新方面,与旧的GregorianCalendar
-class(这是一个多合一类型)相比。用户必须开始考虑为他们的问题和用例选择合适的时间类型。
回答by Sergey Ponomarev
In simple words, the line
简单来说,这条线
ZonedDateTime.parse('2014-04-23', DateTimeFormatter.ISO_OFFSET_DATE_TIME)
throws an exception:
抛出异常:
Text '2014-04-23' could not be parsed at index 10
java.time.format.DateTimeParseException: Text '2014-04-23' could not be parsed at index 10
It looks like a bug for me.
对我来说这看起来像是一个错误。
I used this workaround:
我使用了这个解决方法:
String dateAsStr = '2014-04-23';
if (dateAsStr.length() == 10) {
dateAsStr += 'T00:00:00';
}
ZonedDateTime.parse(dateAsStr, DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.systemDefault()));
回答by Dahar Youssef
Just an example conversions, I believe some folks will get the exception below
只是一个例子转换,我相信有些人会得到下面的例外
(java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-10-24T18:22:09.800Z of type java.time.Instant)
if they try
如果他们尝试
LocalDateTime localDateTime = LocalDateTime.from(new Date().toInstant());
to resolve the issue, please pass in Zone -
要解决此问题,请传入 Zone -
LocalDateTime localDateTime = LocalDateTime.from(new Date()
.toInstant().atZone(ZoneId.of("UTC")));
回答by anon58192932
If coming from Google:
如果来自谷歌:
Instead of doing:
而不是做:
ZonedDateTime.from(new Date().toInstant());
Try this:
尝试这个:
ZonedDateTime.ofInstant(new Date(), ZoneId.of("UTC"));