如何获取不同时区的LocalTime? [英] How to get LocalTime at different time-zone?

查看:285
本文介绍了如何获取不同时区的LocalTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道LocalTime与时区无关。但我想获得中部标准时间(CST)的小时数。我所得到的只是时间在字符串中:

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

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

这很好,但是服务器在不同时区运行。因此它将解释为世界标准时间上午11点。我希望LocalTime在CST中。我需要在CST中进行调用,以便可以调用LocalTime.isAfter方法。

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 so I can invoke LocalTime.isAfter methods.

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


推荐答案

LocalDateTime.now() 实际上是 LocalDateTime.now(Clock.systemDefaultZone())的快捷方式,其中 Clock.class 代表某个日期时间瞬间(参阅文档)和静态方法 systemDefaultZone()返回PC的日期时间点。

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.

在您的情况下,可以在其他区域使用时钟(ID为 CST的区域不存在,但是您可以选择 America / Chicago)-请参阅说明在此答案中)。

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 无法正确理解任务。在这种情况下,将 currentTime 而不是 startTime 转换为所需区域实际上更容易。

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")));

或作为Ole V.V.提醒:

or, as Ole V.V. reminded:

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

然后可以将其与未修改的 startTime 进行比较(在这种情况下-11:00)

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

这篇关于如何获取不同时区的LocalTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆