Home » Java » How to set a timezone with org.joda.time?

How to set a timezone with org.joda.time?

Posted by: admin December 28, 2021 Leave a comment

Questions:

I want to parse a string into DateTime object:

DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy HH:mm");
DateTime dt = fmt.parseDateTime(stringDate + " " +     stringTime).withZone(DateTimeZone.forID("Europe/Dublin"));

If I introduce time 06/22/2014 10:43 I get

06/22/2014 8:43 +0100,

but I want to get

06/22/2014 10:43 +0100

How can I do this?

Answers:

You should apply the timezone to the formatter, not to the DateTime. Otherwise, the date will have been parsed already in your local timezone, and you’re merely transposing it to your desired timezone.

DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy HH:mm")
                        .withZone(DateTimeZone.forID("Europe/Dublin"));
DateTime dt = fmt.parseDateTime("06/22/2014 10:43");

###

Look at this extended code:

String s = "06/22/2014 10:43";
DateTimeFormatter fmt = DateTimeFormat.forPattern("M/d/yyyy HH:mm"); // uses local zone
DateTime dt1 = fmt.parseDateTime(s).withZone(DateTimeZone.forID("Europe/Dublin"));
DateTime dt2 = fmt.withZone(DateTimeZone.forID("Europe/Dublin")).parseDateTime(s);
DateTime dt3 =
  fmt.parseDateTime(s).withZoneRetainFields(DateTimeZone.forID("Europe/Dublin"));
System.out.println(dt1); // 2014-06-22T09:43:00.000+01:00 (from my zone Berlin to Dublin)
System.out.println(dt2); // 2014-06-22T10:43:00.000+01:00
System.out.println(dt3); // 2014-06-22T10:43:00.000+01:00