javadatetimetimezonejodatimedatetime-parsing

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


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?


Solution

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