乔达日期时间。如何将时区设置为解析的 DateTime?

joda Datetime. How to SET timezone to the parsed DateTime?

我正在使用 Scala 和 play 框架。我想用简单的日期解析字符串并说它在 UTC 中。所以如果我有 2018-10-04 我想得到 2018-10-04T00:00:00.000Z

有了这个:

DateTime.parse("2018-10-04", DateTimeFormat.forPattern("yyyy-mm-dd")).withZone(DateTimeZone.UTC)

如果我有 +2 时区,我会一直收到 2018-10-03T22:00:00.000Z。怎么就说已经是UTC了?

一种方法是使用 LocalDatetime 最初忽略时区:

scala> LocalDateTime.parse("2018-10-04", DateTimeFormat.forPattern("yyyy-MM-dd"))
res11: org.joda.time.LocalDateTime = 2018-10-04T00:00:00.000

然后你可以使用 toDateTime 使这个 UTC:

scala> LocalDateTime.parse("2018-10-04", DateTimeFormat.forPattern("yyyy-MM-dd")).toDateTime(DateTimeZone.UTC)
res12: org.joda.time.DateTime = 2018-10-04T00:00:00.000Z

另外:您应该使用 MM(月)而不是 mm(分钟)。

首先是进口。

import org.joda.time.{DateTime, DateTimeZone}
import org.joda.time.format.DateTimeFormat

由于时间部分是固定的,我们可以为时间部分使用常量后缀。

val timeString = "T00:00:00.000Z"

我们使用字符串插值将其附加到传入日期。

DateTime.parse(s"2018-10-04$timeString", DateTimeFormat.forPattern("yyyy-mm-dd'T'HH:mm:ss.SSSZ")).withZone(DateTimeZone.UTC)