Unable to obtain ZonedDateTime from TemporalAccessor using DateTimeFormatter and ZonedDateTime in Java 8
datetime-format, java, java-8, java-time, timezone
Solution
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;
}
Problem
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; } ``` In my case: - fecha is '15/06/2014' - ConstantesFechas.FORMATO_DIA is 'dd/MM/yyyy' - obtenerZonaHorariaServidor returns 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 Any tips? I've been trying different combinations of parsing and using TemporalAccesor, but without any luck so far.