Java 8 - Convert LocalDate to OffsetDateTime

Sandro Rey picture Sandro Rey · Jul 26, 2019 · Viewed 13.2k times · Source

I like to know if it is possible to convert in Java 8 from LocalDate to OffsetDateTime.

For example assume that I have got this LocalDate:

1992-12-28

Then I would like to have it converted to this OffsetDateTime:

1992-12-28T00:00-03:00

Assume that we know the time zone, for example America/Santiago.

Answer

Ole V.V. picture Ole V.V. · Jul 26, 2019

I took the freedom of editing some assumptions into your question. Some reasonable ones, IMHO, but you should check. Please correct if there’s something wrong there. Under those assumption the correct conversion is:

    ZoneId zone = ZoneId.of("Europe/Madrid");
    LocalDate date = LocalDate.of(2019, Month.JULY, 27);
    OffsetDateTime odt = date.atStartOfDay(zone)
            .toOffsetDateTime();
    System.out.println(odt);

Output:

2019-07-27T00:00+02:00

Java knows about summer time (DST) and finds the correct offset for the time zone taking summer time into account. The atStartOfDay method that I call yields a ZonedDateTime, that is a date and time with time zone. It has a toOffsetDateTime method for converting to the OffsetDateTime that you asked for.