在scala slick中使用datetime / timestamp

时间:2017-06-16 12:39:48

标签: scala playframework timestamp playframework-2.0

有一种在scala中使用日期时间/时间戳的简单方法吗?什么是最佳做法?我目前正在使用" date"坚持数据,但我也想坚持现在的时间。 我努力设定日期。这是我的代码:

val now = new java.sql.Timestamp(new java.util.Date().getTime)

我也试过这样做:

val now = new java.sql.Date(new java.util.Date().getTime)

将演变中的数据类型更改为" timestamp"时,出现错误:

case class MyObjectModel(
                               id: Option[Int],
                               title: String,
                               createdat: Timestamp,
                               updatedat: Timestamp,
                               ...)

object MyObjectModel{
  implicit val myObjectFormat = Json.format[MyObjectModel]
}

控制台:

app\models\MyObjectModel.scala:31: No implicit format for 
java.sql.Timestamp available.
[error]   implicit val myObjectFormat = Json.format[MyObjectModel]
[error]                                               ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

更新

object ProcessStepTemplatesModel {
  implicit lazy val timestampFormat: Format[Timestamp] = new Format[Timestamp] {
    override def reads(json: JsValue): JsResult[Timestamp] = json.validate[Long].map(l => Timestamp.from(Instant.ofEpochMilli(l)))

    override def writes(o: Timestamp): JsValue = JsNumber(o.getTime)
  }
  implicit val processStepFormat = Json.format[ProcessStepTemplatesModel]
}

2 个答案:

答案 0 :(得分:1)

尝试在代码中使用此功能

implicit object timestampFormat extends Format[Timestamp] {
    val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'")
    def reads(json: JsValue) = {
      val str = json.as[String]
      JsSuccess(new Timestamp(format.parse(str).getTime))
    }
    def writes(ts: Timestamp) = JsString(format.format(ts))
  }

它(JS)以JS兼容格式序列化,如下所示“2018-01-06T18:31:29.436Z”

请注意:隐含对象在使用之前应在代码中被删除

答案 1 :(得分:-1)

我猜你的问题是在What's the standard way to work with dates and times in Scala? Should I use Java types or there are native Scala alternatives?处理的。

使用Java 8" java.time"。

在这个主题中你提到了Slick(Scala数据库库),但你得到的错误来自一个Json库,它说你没有java.sql.Timestamp到Json的转换器。在不知道您使用哪个Json库的情况下,很难用一个有效的例子来帮助您。