I have a date and time in UTC in a LocalDateTime lastUpdated
. I would like to display time and date for given zone, but no matter the zone I get the same time of day. For the following code:
System.out.println(lastUpdated);
System.out.println(lastUpdated.atZone(ZoneId.of("Europe/Paris")));
System.out.println(lastUpdated.atZone(ZoneId.of("America/Los_Angeles")));
I am getting:
2018-05-26T21:33:46
2018-05-26T21:33:46+02:00[Europe/Paris]
2018-05-26T21:33:46-07:00[America/Los_Angeles]
but what I would like to get is:
2018-05-26T21:33:46
2018-05-26T**23**:33:46+02:00[Europe/Paris]
2018-05-26T**14**:33:46-07:00[America/Los_Angeles]
The zone information is optional for me. I just need the proper time at zone. Is there a way to achieve it?
I have the impression that you're confusing and equating "no timezone information" with "UTC time zone... Because when I don't say what's the time zone it's UTC... Right?"
Wrong. When you don't say what's the time zone then you don't have any specific information regarding the time zone.
So your 2018-05-26T21:33:46 is not a date and time, UTC, it's the notion of a date and a time at this date, without knowing that the concept of time zones exists. It's what you obtain when you go ask someone what date is it today and what time is it. No, they won't think that you might also want to consider that it is in the time zone that you're currently in. The guy will simply not think at all that there is such a thing as time zones, and yet he will be able to tell what day and time it is.
So, to convert a datetime, UTC, to a datetime in other time zones, you do that:
ZonedDateTime time = lastUpdated.atZone(ZoneId.of("UTC"));
System.out.println(time);
System.out.println(time.withZoneSameInstant(ZoneId.of("Europe/Paris")));
System.out.println(time.withZoneSameInstant(ZoneId.of("America/Los_Angeles")));