10

I'm parsing timestamps. They are forced to my local time zone (Europe/London) when I read them in. I want to preserve the original time zone offset instead.

scala> val fmt = org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis()

scala> val t = fmt parseDateTime ("2012-04-16T23:00:45-04:00")
t: org.joda.time.DateTime = 2012-04-17T04:00:45.000+01:00

scala> t.getDayOfMonth
res2: Int = 17

scala> fmt print t
res1: java.lang.String = 2012-04-17T04:00:45+01:00

In this example, a time stamp from America/New_York is forced to Europe/London. When I convert the DateTime back to a String, I want to get back the original string I fed in.

Additionally, when I ask the timestamp what day of the month it's from, I want it to say it's from the 16th (because that's what the date was in the place it was generated), not the 17th (even though that's what the date was in my time zone at the same instant).

How do I do this?

dave4420
  • 46,404
  • 6
  • 118
  • 152

1 Answers1

18

Try creating a DateTimeFormatter with offset parsing enabled. This should cause parsed DateTime objects to retain the offset from the string that was originally parsed.

If that doesn't work, you may need to store the time zone separately. Then, to print a date, you retrieve the date itself, and the target time zone. Set the formatter with the desired time zone, and use it to format the date.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • 5
    Never knew they offset parser would be turned off by default. Seems strange for the ISODateTimeFormat to behave that way. Using the decorator described in the docs, using `ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(dateAsString);` resolved my issue. Thanks for the answer. http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormatter.html – Snekse May 01 '12 at 17:20