【问题标题】:How to parse String containing date and timezone to DateTime如何将包含日期和时区的字符串解析为 DateTime
【发布时间】:2018-10-17 19:34:34
【问题描述】:

我有这样的字符串,可以像这样格式化(取决于时区,例如):

“2018-10-17T15:33:15 UTC”

"2018-10-17T17:03:00 欧洲/布拉格

“2018-10-18T12:00:00 America/Kentucky/Monticello”

所以这些字符串最后包含区域 id

如何将此类字符串解析为日期时间?

我在尝试什么:

val dateString = "2018-10-18T12:00:00 America/Kentucky/Monticello"

    ISODateTimeFormat
    .dateTimeParser()
    .parseDateTime(dateString)

更新:

我也试过了:

val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss zzzz")


val parsed: Date = simpleDateFormat.parse(dateString)

但是无法解析

【问题讨论】:

  • 我建议你远离SimpleDateFormat 类。它不仅过时了,而且出了名的麻烦。今天我们在java.time, the modern Java date and time API 中做得更好。 SimpleDateFormat 不会给你任何你不能从 java.time 和 Joda-Time 得到的东西(我认为你从那里得到了 ISODateTimeFormat)。

标签: datetime kotlin timezone datetime-parsing


【解决方案1】:

您可以创建自己的DateTimeFormatter

val date1 = "2018-10-17T15:33:15 UTC"
val date2 = "2018-10-17T17:03:00 Europe/Prague"
val date3 = "2018-10-18T12:00:00 America/Kentucky/Monticello"

//with JDK
val formatter = java.time.format.DateTimeFormatterBuilder()
    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    .optionalStart()
    .appendLiteral(' ')
    .parseCaseSensitive()
    .appendZoneRegionId()
    .toFormatter();
println(ZonedDateTime.parse(date1, formatter))
println(ZonedDateTime.parse(date2, formatter))
println(ZonedDateTime.parse(date3, formatter))

//With Joda Time
val jodaFormatter = org.joda.time.format.DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss ZZZ").toFormatter()
println(jodaFormatter.parseDateTime(date1))
println(jodaFormatter.parseDateTime(date2))
println(jodaFormatter.parseDateTime(date3))

此格式化程序只能解析“Europe/Prague”,不能解析“Europe/Praga”。您可以在此处找到所有支持的区域 ID:https://www.mkyong.com/java8/java-display-all-zoneid-and-its-utc-offset/

【讨论】:

  • 我无法使用 DateTimeFormatter.ISO_LOCAL_DATE_TIME,有什么替代方法?
  • 为什么不呢?你的环境是什么? JDK?库?
  • 我正在编写 Android 应用程序 - 这需要我无法申请的最低 API 级别 26(我的最低要求是 21)
  • 是的,我愿意。我刚刚添加了一个 JodaTime 示例。我不是 Android 开发者,所以我不知道你是否可以使用 JodaTime。
  • 好答案。从问题中我看不出可选部分的原因,因为它在所有输入字符串中,没有它你无法解析为ZonedDateTimeparseCaseSensitive 也是默认的,所以你不需要明确声明它。
猜你喜欢
  • 1970-01-01
  • 2012-02-03
  • 2015-09-23
  • 1970-01-01
  • 2013-11-21
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
相关资源
最近更新 更多