我正在解析时间戳。当我读入它们时,它们被强制为我的本地时区(欧洲/伦敦)。我想保留原始时区偏移量。
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
在此示例中,从 America/New_York 的时间戳被强制发送到 Europe/London。当我将 DateTime 转换回字符串时,我想取回我输入的原始字符串。
此外,当我询问时间戳是从一个月的哪一天开始时,我希望它说它是从 16 日开始的(因为这就是日期位于生成日期的位置),而不是 17 日(即使那是同一时刻我所在时区的日期)。
我该怎么做?
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?
发布评论
评论(2)
尝试创建一个
DateTimeFormatter
这应该会导致解析的DateTime
对象保留最初解析的字符串的偏移量。如果这不起作用,您可能需要单独存储时区。然后,要打印日期,您需要检索日期本身以及目标时区。 设置格式化程序与所需的时区,并用它来格式化日期。
Try creating a
DateTimeFormatter
with offset parsing enabled. This should cause parsedDateTime
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.
java.time
下面显示的是 Joda-Time 主页上的通知< /a>:
使用现代日期时间 API 的解决方案
您不需要使用
java.time
API 启用偏移量解析,这是OffsetDateTime#parse
。将日期时间字符串解析为OffsetDateTime
后,如果需要,可以将其转换为另一个具有不同时区偏移量的OffsetDateTime
。演示:
输出:
在线演示
/ /编辑
值得一提的是https://stackoverflow.com/users/5772882/anonymous:
从跟踪:日期时间。
java.time
Shown below is a notice on the Joda-Time Home Page:
Solution using modern date-time API
You do not need to enable offset parsing using the
java.time
API, it is the default behaviour ofOffsetDateTime#parse
. Once you have parsed your date-time string into anOffsetDateTime
, you can convert it anotherOffsetDateTime
with a different time zone offset if you need one.Demo:
Output:
Online Demo
// EDIT
It is worth mentioning the following comment by https://stackoverflow.com/users/5772882/anonymous:
Learn more about the modern Date-Time API from Trail: Date Time.