Unable to obtain ZonedDateTime from TemporalAccessor using DateTimeFormatter and ZonedDateTime in Java 8

后端 未结 5 1733
礼貌的吻别
礼貌的吻别 2020-11-30 11:11

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 d

5条回答
  •  盖世英雄少女心
    2020-11-30 11:21

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

提交回复
热议问题