Reputation: 43
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?
Upvotes: 2
Views: 3465
Reputation: 2490
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")));
Upvotes: 4
Reputation: 3563
You are using a LocalDateTime
, which is a date and time indication without a timezone, as you would use when you discuss dates and times with people in your own timezone. The atZone
returns a ZonedDateTime
of that date at time as if you were speaking about it at that timezone.
So in order to get the different times you need to convert the ZonedDateTime
to an Instant
, which is a point in time, identified for the entire planet. That Instant
can then be converted into a ZonedDateTime
again.
LocalDateTime lastUpdated = LocalDateTime.now();
ZonedDateTime zonedDateTime = lastUpdated.atZone(ZoneId.of("Europe/Paris"));
System.out.println(zonedDateTime);
ZonedDateTime other = ZonedDateTime.ofInstant(zonedDateTime.toInstant(), ZoneId.of("America/Los_Angeles"));
System.out.println(other);
Output:
2018-05-27T21:53:53.754+02:00[Europe/Paris]
2018-05-27T12:53:53.754-07:00[America/Los_Angeles]
Upvotes: 2