无法使用Java 8中的DateTimeFormatter和ZonedDateTime从TemporalAccessor获取ZonedDateTime [英] Unable to obtain ZonedDateTime from TemporalAccessor using DateTimeFormatter and ZonedDateTime in Java 8

查看:648
本文介绍了无法使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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