Skip to content
Advertisement

Java Time: LocalTime (UTC) to ZonedTime (-05:00) not displaying correct hour

I’m new to using Java’s built in time API. I’m trying to fetch the current time in UTC, and I want to be able to convert that into the timezone of whoever is running the program. Right now I have this code:

Clock clock = Clock.systemUTC();
LocalDateTime time = LocalDateTime.now(clock);
ZonedDateTime zonedTime = time.atZone(ZoneId.systemDefault());
System.out.println("UTC time: " + time + " Local: " + zonedTime);

However, this prints out:

UTC time: 2022-06-01T15:25:57.933673600 Local: 2022-06-01T15:25:57.9336736-05:00

It appears to be fetching the correct timezone, but it’s not applying it to the output. So if I print

time.getHour()
zonedTime.getHour()

They both print out “15.” What’s the correct way to get it to give me the time with the timezone offset applied? The UTC time is 15, but my local time is 10. I want to be able to to convert the UTC to the timezone time.

The reason why is that I’m setting up save files – so I want to record the UTC time of when the file was saved, but then be able to display the time in the timezone of the user when they check the save date on their computers.

Advertisement

Answer

The problem is your use of LocalDateTime. That has no concept of which time zone it’s in – so when you use LocalDateTime.atZone it assumes you want to keep that same local date/time.

The best fix here is to change LocalDateTime.now(clock) to Instant.now(clock). What you’re interested in is “the current instant in time”, not “the local time in UTC”.

Alternatively, use a Clock in the system time zone with ZonedDateTime.now(clock).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement