How to preserve time zone in Joda-Time timestamp?
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.
Additiona开发者_开发百科lly, 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?
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.
精彩评论