edwardmlyte edwardmlyte - 11 days ago 5x
Java Question

Joda Time parse a date with timezone and retain that timezone

I want to parse a date, which was created with a specific timezone, convert it to a format and return it. The conversion works but the timezone offset is always set to +0000 with the time difference being added/subtracted as necessary. How can I get it to format and keep the offset correct?

I expect this: 2012-11-30T12:08:56.23+07:00

But get this: 2012-11-30T05:08:56.23+00:00


public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSZZ";

public static String formatDateToISO8601Standard(Date date) {
DateTime dateTime = new DateTime(date);
DateTimeFormatter df = DateTimeFormat.forPattern(ISO_8601_DATE_FORMAT);
return dateTime.toString(df);

Test class:

private static final String DATE_WITH_TIMEZONE = "30 11 2012 12:08:56.235 +0700";
private static final String EXPECTED_DATE_WITH_TIMEZONE = "2012-11-30T12:08:56.23+07:00";

@Test public void testFormattingDateWithSpecificTimezone() throws Exception {
String result = JodaDateUtil.formatDateToISO8601Standard(createDate(DATE_WITH_TIMEZONE));
assertEquals("The date was not converted correctly", EXPECTED_DATE_WITH_TIMEZONE, result); }

private Date createDate(String dateToParse) throws ParseException {
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.parseDateTime(dateToParse);
Date date = temp.toDate();
return date; }


Basically, once you parse the date string [in your createDate() method] you've lost the original zone. Joda-Time will allow you to format the date using any zone, but you'll need to retain the original zone.

In your createDate() method, the DateTimeFormatter "df" can return the zone that was on the string. You'll need to use the withOffsetParsed() method. Then, when you have your DateTime, call getZone(). If you save this zone somewhere or somehow pass it to your formatting routine, then you can use it there by creating a DateTimeFormatter "withZone" and specifying that zone as the one you want on the format.

As a demo, here's some sample code in a single method. Hopefully, it'll help change your code the way you want it to run.

  public static void testDate() 
    DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
    DateTime temp = df.withOffsetParsed().parseDateTime("30 11 2012 12:08:56.235 +0700");
    DateTimeZone theZone = temp.getZone();

    Date date = temp.toDate();

    DateTime dateTime = new DateTime(date);
    DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
    DateTimeFormatter df3 = df2.withZone(theZone);