Reputation: 3421
I would like to set a timezone over a constant DateTime.
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.
Upvotes: 1
Views: 4096
Reputation: 316
Looking at your implementation, you want to make DateTime to behave like Calendar. Since Calendar is mutable, and DateTime is not, why not use the MutableDateTime - a mutable version of DateTime. See my code below:
//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();
I hope this one works for you. Cheer!
Upvotes: 1
Reputation: 1500165
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.)
Upvotes: 7