无法在 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: 文本 '15/06/2014' 不能被解析:无法从 TemporalAccessor 获取 ZonedDateTime:{},ISO 解析为 java.time.format.Parsed 类型的 2014-06-15

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:

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:

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

相关文章