6

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?

Filosssof
  • 1,288
  • 3
  • 17
  • 37
  • Sorry, after some spent time i found the answer: http://stackoverflow.com/questions/19002978/in-joda-time-how-to-convert-time-zone-without-changing-time Thanks for @jgm – Filosssof Jun 23 '14 at 13:46

2 Answers2

11

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");
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
1

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
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126