Rectangle 27 0

java In joda time how to convert time zone without changing time?


Use this situation carefully because the it may throw an exception when the time shift if you are using it in a Daylight savings configured environment. If you have the date in text you may prefer a solution like this stackoverflow.com/questions/5451152/

Note
Rectangle 27 0

java In joda time how to convert time zone without changing time?


DateTime
DateTime dt = new LocalDateTime(timestamp.getTime()).toDateTime(DateTimeZone.UTC);
LocalDateTime
LocalDateTime dt = new LocalDateTime(t.getTime());
java.sql.Timestamp
java.util.Date
timestamp

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

It worked using LocalDateTime but why DateTime is behaving like this? Is there any solution for it?

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.

Please check the edit, I have mentioned the output there

Note
Rectangle 27 0

java In joda time how to convert time zone without changing time?


DateTime localDt = new DateTime(timestamp.getTime())
    .withZoneRetainFields(DateTimeZone.UTC)
    .withZone(DateTimeZone.getDefault());
new DateTime(timestamp.getTime())
    .withZoneRetainFields(DateTimeZone.UTC)
    .withZone(DateTimeZone.getDefault());

Breaking it down: This gives you a DateTime corresponding to your timestamp, specifying that it is in UTC:

If your timestamp is: 2015-01-01T00:00:00.000-0500 (this is local time [for me])

This gives you a DateTime but with the time converted to your local time:

Note
Rectangle 27 0

java In joda time how to convert time zone without changing time?


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();
}
Note