Joda Time parse a date with timezone and retain that timezone

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

    System.out.println(dateTime.toString(df2));
    System.out.println(dateTime.toString(df3));

  }

Leave a Comment