简体   繁体   English

如何在不同的时区获取 LocalTime?

[英]How to get LocalTime at different time-zone?

I understand that LocalTime is time-zone agnostic.我知道 LocalTime 是时区不可知的。 But I would like to get hours in Central Standard Time (CST).但我想在中央标准时间 (CST) 获得数小时。 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.因此它会将其解释为 UTC 时间上午 11 点。 I want LocalTime to be in CST.我希望 LocalTime 在 CST 中。 I need to in CST so I can invoke LocalTime.isAfter methods.我需要在 CST 中调用 LocalTime.isAfter 方法。

LocalTime currentTime = LocalTime.now();
boolean afterEleven = currentTime.isAfter(startTime);

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. LocalDateTime.now()实际上是LocalDateTime.now(Clock.systemDefaultZone())的快捷方式,其中Clock.class表示某个日期时间瞬间( 请参阅文档),静态方法systemDefaultZone()返回您的日期时间瞬间个人电脑。

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 ).在您的情况下,可以将“时钟”用于不同的区域(id="CST" 的区域不存在,但您可以选择“America/Chicago” - 请参阅此答案中的解释)。

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

UPD Didn't understand the task properly. UPD没有正确理解任务。 In this case it's actually easier to convert currentTime instead of startTime to needed zone.在这种情况下,将currentTime而不是startTime转换为所需的区域实际上更容易。

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

or, as Ole VV reminded:或者,正如 Ole VV 提醒的那样:

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

then you can compare it with unmodified startTime (in this case - 11:00)然后你可以将它与未修改的startTime进行比较(在这种情况下 - 11:00)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM