无法使用Java 8中的DateTimeFormatter和ZonedDateTime从TemporalAccessor获取ZonedDateTime

编程入门 行业动态 更新时间:2024-10-11 11:16:22
本文介绍了无法使用Java 8中的DateTimeFormatter和ZonedDateTime从TemporalAccessor获取ZonedDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近搬到了Java 8,希望能更轻松地处理本地和分区时间。

I recently moved to Java 8 to, hopefully, deal with local and zoned times more easily.

但是,我认为,我面临着一个简单的问题解析简单日期时出现问题。

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

在我的情况下:

  • 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

任何提示?我一直在尝试不同的解析和使用TemporalAccesor的组合,但到目前为止没有任何运气。

Any tips? I've been trying different combinations of parsing and using TemporalAccesor, but without any luck so far.

祝你好运

推荐答案

我不确定为什么它不起作用(可能是因为你的输入没有时间/时区信息)。一种简单的方法是首先将您的日期解析为 LocalDate (没有时区或时区信息)然后创建 ZonedDateTime :

I am not sure why it does not work (probably because your input does not have time/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:

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

更多推荐

无法使用Java 8中的DateTimeFormatter和ZonedDateTime从TemporalAccessor获取ZonedDateTime

本文发布于:2023-10-29 00:55:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538230.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DateTimeFormatter   Java   TemporalAccessor   ZonedDateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!