Search code examples
javadate

How to get LocalTime at different time-zone?


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.


Solution

  • 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)