JodaTime Setting TimeZone over Existing DateTime

I would like to set a timezone over a constant DateTime.

  1. I want to create a single DateTime in a certain timezone.
  2. Set a new timezone to get a calculated DateTime object.

For example:

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

How would I be able to get this done using the Joda-time API.

Jon Skeet
people
quotationmark

Assuming you want "the same instant, just in a different time zone" then you want withZone.

It's not setZone, because DateTime (like many types in Joda Time) is immutable. Instead, you use withZone and use the result. For example:

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

Output:

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

Note that if you don't specify the time zone when you construct a DateTime, it will use the system default time zone, which is rarely a good idea. (As noted in comments, if you're writing client code is may be that you do want the system default time zone - but I view it as best practice to state that explicitly, so that it's really clear to anyone who might consider using the code in a different context.)

people

See more on this question at Stackoverflow