I am getting UTC timestamp from database which is I am setting into a JodaTime DateTime
instance
DateTime dt = new DateTime(timestamp.getTime())
You can use the withZoneRetainFields()
method of DateTime
to alter the timezone without altering the numerals in the date.
If your timestamp is: 2015-01-01T00:00:00.000-0500 (this is local time [for me])
Try this:
DateTime localDt = new DateTime(timestamp.getTime())
.withZoneRetainFields(DateTimeZone.UTC)
.withZone(DateTimeZone.getDefault());
2014-12-31T19:00:00.000-05:00
Breaking it down: This gives you a DateTime corresponding to your timestamp, specifying that it is in UTC:
new DateTime(timestamp.getTime())
.withZoneRetainFields(DateTimeZone.UTC)
2015-01-01T00:00:00.000Z
This gives you a DateTime but with the time converted to your local time:
new DateTime(timestamp.getTime())
.withZoneRetainFields(DateTimeZone.UTC)
.withZone(DateTimeZone.getDefault());
2014-12-31T19:00:00.000-05:00
Here's how I do it:
private DateTime convertLocalToUTC(DateTime eventDateTime) {
// get your local timezone
DateTimeZone localTZ = DateTimeZone.getDefault();
// convert the input local datetime to utc
long eventMillsInUTCTimeZone = localTZ.convertLocalToUTC(eventDateTime.getMillis(), false);
DateTime evenDateTimeInUTCTimeZone = new DateTime(eventMillsInUTCTimeZone);
return evenDateTimeInUTCTimeZone.toDate();
}
I had the same problem. After reading this set of useful answers, and given my particular needs and available objects, I solved it by using another DateTime constructor:
new DateTime("2012-04-23T18:25:46.511Z", DateTimeZone.UTC)
You can use class LocalDateTime
LocalDateTime dt = new LocalDateTime(t.getTime());
and convert LocalDateTime
to DateTime
DateTime dt = new LocalDateTime(timestamp.getTime()).toDateTime(DateTimeZone.UTC);
Joda DateTime
treats any time in millis like "millis since 1970y in current time zone". So, when you create DateTime
instance, it is created with current time zone.
Also i have another approach that was very helpful for me. I wanted to have my workflow thread temporary changed to an specific Timezone (conserving the time), and then when my code finishes, i set the original timezone again. It turns out that when you are using joda libraries, doing:
TimeZone.setDefault(TimeZone.getTimeZone(myTempTimeZone));
TimeZone.setDefault(timeZone);
It's not enough. We also need to change the TimeZone in DateTimeZone as follows:
@Before
public void setUp() throws Exception {
timeZone = TimeZone.getDefault();
dateTimeZone = DateTimeZone.getDefault();
}
@After
public void tearDown() throws Exception {
TimeZone.setDefault(timeZone);
DateTimeZone.setDefault(dateTimeZone);
}
@Test
public void myTest() throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone(myTempTimeZone));
DateTimeZone.setDefault(DateTimeZone.forID(myTempTimeZone));
//TODO
// my code with an specific timezone conserving time
}
Hope it helps to somebody else as well.