2017-06-16 133 views
1

在scala中使用datetime/timestamp有沒有簡單的方法?什麼是最佳做法?我目前使用「日期」來保存數據,但我也想堅持當前的時間。 我正在努力設定日期。這是我的代碼:在scala中使用datetime/timestamp

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

我也試着這樣做:

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

當改變我的變陣爲 「時間戳」 的數據類型,我得到了一個錯誤:

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] 
} 

回答

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)) 
    } 

這是(DE)連載中像下面這樣的JS兼容格式 「2018-01-06T18:31:29.436Z」

請注意:隱含對象在使用前應在代碼中被刪除