Java 8 Anonymous Anonymous Date / Time

I am trying to save a timestamp field in postgresql using anorm. In scala, the date / time of the code is stored as an instance of java.time.Instant (someTime variable)

DB.withConnection() { implicit c => 
    SQL("INSERT INTO t_table(some_time) values ({someTime})").on('someTime -> someTime)
}

But abnormalities cannot work with him now (Play 2.3.7).

What is the best way to make it work?

0
source share
1 answer

I believe most people use JodaTime, so that might explain why it is missing. If it is not part of Anorm, you can write your own converter.

This is not verified, but it looks something like

import java.time.Instant
import java.time.format.DateTimeFormatter
import java.util.TimeZone

import anorm._

object InstantAnormExtension {
  val dateFormatGeneration = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss-Z")

  implicit def rowToDateTime: Column[Instant] = Column.nonNull { (value, meta) =>
    val MetaDataItem(qualified, nullable, clazz) = meta
    value match {
      case ts: java.sql.Timestamp => Right(ts.toInstant)
      case d: java.sql.Date => Right(d.toInstant)
      case str: java.lang.String => Right(Instant.from(dateFormatGeneration.parse(str)))
      case _ => Left(TypeDoesNotMatch("Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass) )
    }
  }
  implicit val dateTimeToStatement = new ToStatement[Instant] {
    def set(s: java.sql.PreparedStatement, index: Int, aValue: Instant): Unit = {
      if(aValue == null) {
        s.setTimestamp(index, null)
      } else {
        s.setTimestamp(index, java.sql.Timestamp.from(aValue) )
      }
    }
  }
}
+2
source

All Articles