首页 > 解决方案 > Scala / Joda - Joda DateTimeFormat 不适用

问题描述

我想从数据库中检索日期并保留其格式"20200406T145511.067Z"。例如,当我尝试将其解析为 Joda DateTime 时,格式更改为"2020-04-06T14:55:11.067+01:00". 由于这个问题,我试图明确说明 Joda DateTime 应该返回的 DateTimeFormat "yyyyMMdd'T'HHmmss.SSS'Z'",但它似乎并不适用。我想以DateTime我期望的格式返回一个对象(例如"20200406T145511.067Z")。

    val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
    val itemDateTime = dateTimeFormat.parseDateTime(record.get("itemDateTime").asString)

    println("Neo4J: " + record.get("assetDateTime").asString) // Neo4J: 20200406T145511.067Z
    println("Joda: " + assetDateTime) // Joda: 2020-04-06T14:55:11.067+01:00

    val lastUpdatedDateTime = dateTimeFormat.parseDateTime(record.get("lastUpdatedDateTime").asString)

    println("Neo4J: " + record.get("lastUpdatedDateTime").asString) // Neo4J: 20200406T145511.383Z
    println("Joda: " + lastUpdatedDateTime) // Joda: 2020-04-06T14:55:11.383+01:00

编辑:我已经更新了我的代码以返回正确的类型DateTime,但我现在得到一个无效的格式错误 -

java.lang.IllegalArgumentException: Invalid format: "20200406T161516.856Z" is malformed at "1516.856Z"

我不明白为什么会这样。任何帮助,将不胜感激。

更新代码:

    val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
    val itemDateTime = dateTimeFormat.parseDateTime(record.get("itemDateTime").asString)
    val itemDateTimeFormat = dateTimeFormat.print(itemDateTime)
    val lastUpdatedDateTime = dateTimeFormat.parseDateTime(record.get("lastUpdatedDateTime").asString)
    val lastUpdatedDateTimeFormat = dateTimeFormat.print(lastUpdatedDateTime)
    if (lastUpdatedDateTime.isAfter(itemDateTime) new DateTime(lastUpdatedDateTimeFormat) else new DateTime(itemDateTimeFormat)

标签: scaladatetimejodatime

解决方案


您可以使用 ISODateTimeFormatter 解析

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.ISODateTimeFormat

// val inputDt = record.get("itemDateTime").asString 
// let's imagine we have a data as following:
val inputDt = "20200406T161516.856Z"
val dateTimeFormat = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss.SSS'Z'")
val itemDateTime = dateTimeFormat.parseDateTime(inputDt)
val parsedDate = DateTime.parse(itemDateTime.toString, ISODateTimeFormat.dateTimeParser());
println(parsedDate) // 2020-04-06T16:15:16.856Z
val result: String = dateTimeFormat.print(parsedDate) //NOTE: return type is String
println(result) // 20200406T161516.856Z

更新:

文档

在内部,该类包含两条数据。首先,它将日期时间保存为从 Java 纪元 1970-01-01T00:00:00Z 开始的毫秒数。

我从这句话中理解的内容,无论您的格式如何,它都保持为Long(内部状态),并且它对客户的表示可能会因格式化程序和年表而有所不同。

我们能做什么,它不是应用程序级别的格式。我们可能需要返回一个特定的格式化日期,所以我们可以在需要时对其进行转换,例如:为 rest 客户端返回一个 json :

val dateFormat = "yyyyMMdd'T'HHmmss.SSS'Z'"
val dateTimeWrites: Writes[DateTime] = new Writes[DateTime] {
  def writes(d: DateTime): JsValue = JsString(d.toString())
}

推荐阅读