1

is there an easy way to use datetime/timestamp in scala? What's best practice? I currently use "date" to persist data, but I'd also like to persist the current time. I'm struggling to set the date. This is my code:

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

I also tried to do this:

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

When changing the datatype in my evolutions to "timestamp", I got an error:

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

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

Console:

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

Update:

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]
}
Felix
  • 5,452
  • 12
  • 68
  • 163

2 Answers2

1

try using this in your code

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

it is (de)serialized in a JS compatible format like the following "2018-01-06T18:31:29.436Z"

please note: the implicit object shall be decleared in the code before it is used

il.bert
  • 232
  • 1
  • 3
  • 11
-1

I guess your question is handled in What's the standard way to work with dates and times in Scala? Should I use Java types or there are native Scala alternatives?.

Go with Java 8 "java.time".

In the subject you mention Slick (Scala Database Library) but the error you got comes from a Json library and it says that you don't have a converter for java.sql.Timestamp to Json. Without knowing which Json library you are using it's hard to help you with a working example.

nano4711
  • 1
  • 2