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.
Thank you for your time!!
CodePudding user response:
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)
.
CodePudding user response:
For those that may come across this in the future, here is the same code with the fix from the selected answer applied:
Instant time = Instant.now();
ZonedDateTime zonedTime = time.atZone(ZoneId.systemDefault());
System.out.println("UTC time: " time " Local: " zonedTime.toOffsetDateTime());