How to use Joda DateTime with Play Json How to use Joda DateTime with Play Json json json

How to use Joda DateTime with Play Json


Expecting a better alternative, here my workaround:

val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"val jodaDateReads = Reads[DateTime](js =>  js.validate[String].map[DateTime](dtString =>    DateTime.parse(dtString, DateTimeFormat.forPattern(dateFormat))  ))val jodaDateWrites: Writes[DateTime] = new Writes[DateTime] {  def writes(d: DateTime): JsValue = JsString(d.toString())}val userReads: Reads[User] = (  (JsPath \ "name").read[String] and    (JsPath \ "created").read[DateTime](jodaDateReads)  )(User.apply _)val userWrites: Writes[User] = (  (JsPath \ "name").write[String] and   (JsPath \ "created").write[DateTime](jodaDateWrites)  )(unlift(User.unapply))implicit val userFormat: Format[User] = Format(userReads, userWrites)


In play 2.6, the canonical way to serialize/deserialize joda DateTime json is by using the play-json-joda library. Import the library by updating your build.sbt. Then create json reader and json writers like this :

import play.api.libs.json.JodaWritesimplicit val dateTimeWriter: Writes[DateTime] = JodaWrites.jodaDateWrites("dd/MM/yyyy HH:mm:ss")import play.api.libs.json.JodaReadsimplicit val dateTimeJsReader = JodaReads.jodaDateReads("yyyyMMddHHmmss")