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

JodaTime Setting TimeZone over Existing DateTime

我想在一个恒定的 DateTime 上设置一个时区。

  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。

假设你想要 "the same instant, just in a different time zone" 那么你想要 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,它将使用系统默认时区,这很少是一个好的主意。 (如评论中所述,如果您正在编写客户端代码,则可能是您 do 想要系统默认时区 - 但我认为明确说明是最佳实践,因此对于可能考虑在不同上下文中使用该代码的任何人来说,真的很清楚。)

查看您的实现,您希望 DateTime 的行为类似于 Calendar。由于 Calendar 是可变的,而 DateTime 不是,为什么不使用 MutableDateTime - DateTime 的可变版本。请参阅下面的代码:

    //this is the mutable version of DateTime, set to UTC as default
    MutableDateTime currentTime = new DateTime(2015, 1, 23, 2, 0, DateTimeZone.UTC).toMutableDateTime(); // CONSTANT

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

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

    //if you want to return a value in DateTime datatype
    currentTime.toDateTime();

我希望这个对你有用。加油!