Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get LocalTime at different time-zone?

Tags:

java

date

I understand that LocalTime is time zone agnostic. But I would like to get hours in Central Standard Time (CST) zone. All I am given is time in String:

String start = "11:00" //11 am CST. 
LocalTime startTime = LocalTime.parse(start);

This is good but server is running in different time-zone. So it will interpret it as 11 am UTC. I want LocalTime to be in CST. I need to in CST.

like image 319
Faraz Avatar asked Oct 28 '25 02:10

Faraz


1 Answers

LocalDateTime.now() is actually a shortcut for LocalDateTime.now(Clock.systemDefaultZone()), where Clock.class represents some date-time instant (see docs), and static method systemDefaultZone() returns the date-time instant of your PC.

In your case it's possible to use "clock" for a different zone (zone with id="CST" doesn't exist but you can choose "America/Chicago" instead - see explanation in this answer).

LocalTime currentTime = LocalTime.now(Clock.system(ZoneId.of("America/Chicago")));

UPD Didn't understand the task properly. In this case it's actually easier to convert currentTime instead of startTime to needed zone.

LocalTime currentTime = LocalTime.now(Clock.system(ZoneId.of("Europe/London")));

or, as Ole V.V. reminded:

LocalTime currentTime = LocalTime.now(ZoneId.of("Europe/London"));

then you can compare it with unmodified startTime (in this case - 11:00)

like image 193
amseager Avatar answered Oct 30 '25 16:10

amseager