Search code examples
javautclocaldatezoneddatetimejava-time

How to convert UTC Time to LocalDateTime by using ZonedDateTime


I have found many way to convert localDateTime to LocalDateTime in UTC. But I could not find any way to convert UTC time at localDateTime by using ZonedDateTime. Do you know a way to convert it ?

This is what I used to convert it to UTC. I need a vice versa method .

 ZonedDateTime zonedDate = ZonedDateTime.of(localDateTime, 
ZoneId.systemDefault());


localDateTime.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC)

Solution

  • Don’t use LocalDateTime for a date and time for which you know the UTC offset or time zone. For a date and time in your time zone or another known time zone, use ZonedDateTime. For a date and time for which you know an offset (and here UTC counts as an offset) use OFfsetDateTime.

    Why? LocalDateTime (confusing class name) is a date and time without time zone or offset. Not storing the known offset or time zone is throwing away vital data and is an error waiting to happen.

    One exception: For a date and time in a known time zone in a further future, do store a LocalDateTime and make sure to store the time zone as a separate ZoneId object. This will allow the offset and/or summer time rules (DST rules) for the time zone to be changed between now and that time (which happens more often than we like to think). Only when time draws near and our Java installation may have been updated with the latest zone rules, can we correctly combine the date-time and the zone and obtain the correct moment in time.

    Convert UTC date and time to your time zone

        OffsetDateTime utcDateTime = OffsetDateTime.of(2019, 9, 10, 12, 0, 0, 0, ZoneOffset.UTC);
        System.out.println("UTC date and time: " + utcDateTime);
        ZonedDateTime myDateTime = utcDateTime.atZoneSameInstant(ZoneId.systemDefault());
        System.out.println("Date and time in the default time zone: " + myDateTime);
    

    After I set my time zone to Asia/Istanbul, this snippet output:

    UTC date and time: 2019-09-10T12:00Z
    Date and time in the default time zone: 2019-09-10T15:00+03:00[Asia/Istanbul]
    

    Convert from your time zone to UTC

    For the opposite conversion I prefer:

        OffsetDateTime convertedBackToUtc = myDateTime.toOffsetDateTime()
                .withOffsetSameInstant(ZoneOffset.UTC);
        System.out.println("UTC date and time again: " + convertedBackToUtc);
    
    UTC date and time again: 2019-09-10T12:00Z
    

    Still not using any LocalDateTime.