【问题标题】:Joda DateTime output unexpected difference from gmtJoda DateTime 输出与 gmt 的意外差异
【发布时间】:2015-11-25 00:38:16
【问题描述】:
我的代码:
val pattern = "MM-dd-yy"
val t = DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern)).toDateTime(DateTimeZone.forID("GMT"))
val z = t.getMillis.asInstanceOf[Long]
println("ms= "+z) // expected output: 520560000000 actual output: 520578000000
几个在线 GMT 日期转换器提供与 DateTime 不同的毫秒输出。有人知道为什么吗?
【问题讨论】:
标签:
datetime
jodatime
gmt
【解决方案1】:
在您的解决方案中,您的 本地时区 在解析日期时间时被隐式使用。你应该使用
val t = DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern).withZoneUTC())
强制在 UTC 区域中创建 DateTime。那么,毫秒是520560000000。无需再对其执行toDateTime(DateTimeZone)。
否则,与你的建设
val t = DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern)).toDateTime(DateTimeZone.forID("GMT"))
DateTime 将首先在您的本地 TZ 中创建(即 your TZ 中 07-01-86 的 midnight),然后“转换”为 UTC ,但保留时间戳(即,它将是相同的时间戳,但以 UTC 解释,因此时间部分和日期部分将根据您的本地 TZ 偏移量而变化)。
示例(我的 TZ 是 +02:00):
DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern)) // --> 1986-07-01 00:00 (+02:00)
.toDateTime(DateTimeZone.forID("GMT")) // --> 1986-06-30 22:00 (UTC)
我认为你可以使用 UTC 而不是 GMT,但也有
DateTimeFormat.forPattern(pattern).withZone(...)
您可以在哪里提供您想要的区域。