我知道 LocalTime 与时区无关。但我想获得中部标准时间 (CST) 时区的时间。我得到的只是字符串中的时间:
String start = "11:00" //11 am CST.
LocalTime startTime = LocalTime.parse(start);
Run Code Online (Sandbox Code Playgroud)
这很好,但服务器在不同的时区运行。因此它会将其解释为 UTC 时间上午 11 点。我希望当地时间为 CST。我需要在 CST 中。
LocalDateTime.now()实际上是 的快捷方式LocalDateTime.now(Clock.systemDefaultZone()),其中Clock.class代表某个日期时间瞬间(请参阅文档),静态方法systemDefaultZone()返回 PC 的日期时间瞬间。
在您的情况下,可以将“时钟”用于不同的区域(id =“CST”的区域不存在,但您可以选择“美国/芝加哥” - 请参阅此答案中的说明)。
LocalTime currentTime = LocalTime.now(Clock.system(ZoneId.of("America/Chicago")));
Run Code Online (Sandbox Code Playgroud)
UPD没有正确理解该任务。在这种情况下,转换实际上 currentTime比转换startTime到所需区域更容易。
LocalTime currentTime = LocalTime.now(Clock.system(ZoneId.of("Europe/London")));
Run Code Online (Sandbox Code Playgroud)
或者,正如 Ole VV 提醒的那样:
LocalTime currentTime = LocalTime.now(ZoneId.of("Europe/London"));
Run Code Online (Sandbox Code Playgroud)
然后您可以将其与未修改的进行比较startTime(在本例中 - 11:00)