gpt4 book ai didi

java - JodaTime 在现有日期时间上设置时区

转载 作者:行者123 更新时间:2023-11-29 10:12:27 28 4
gpt4 key购买 nike

我想在一个常量日期时间上设置一个时区。

  1. 我想在特定时区创建一个 DateTime。
  2. 设置新时区以获取计算的 DateTime 对象。

例如:

DateTime currentTime = new DateTime(2015, 1, 23, 2, 0); // CONSTANT

// Looking for something that can perform this type of method.
currentTime.setTimeZone(DateTimeZone.forID("Asia/Tokyo"));
System.out.println("Asia/Tokyo Time" + currentTime);

currentTime.setTimeZone(DateTimeZone.forID("America/Montreal")
System.out.println("America/Montreal Time" + currentTime);

我如何使用 Joda-time API 完成此操作。

最佳答案

假设您想要“同一时刻,只是在不同的时区”,那么您需要 withZone .

它不是 setZone,因为 DateTime(就像 Joda Time 中的许多类型一样)是不可变的。相反,您使用 withZone 并使用结果。例如:

DateTime currentTime = new DateTime(2015, 1, 23, 2, 0, 0, DateTimeZone.UTC);
DateTime tokyo = currentTime.withZone(DateTimeZone.forID("Asia/Tokyo"));
System.out.println("Asia/Tokyo Time" + tokyo);

输出:

Asia/Tokyo Time2015-01-23T11:00:00.000+09:00

请注意,如果您在构造 DateTime指定时区,它将使用系统默认时区,这很少是一个好主意。 (如评论中所述,如果您正在编写客户端代码,则可能是您确实想要系统默认时区 - 但我认为明确说明是最佳实践,因此它是真的对于可能考虑在不同上下文中使用代码的任何人来说都很清楚。)

关于java - JodaTime 在现有日期时间上设置时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28098300/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com