How to preserve time zone in Joda-Time timestamp?

こ雲淡風輕ζ 提交于 2019-12-09 16:53:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5942702/how-to-preserve-time-zone-in-joda-time-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!