Skip to content

Instantly share code, notes, and snippets.

@opensas
Created May 30, 2012 05:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save opensas/2833989 to your computer and use it in GitHub Desktop.
Save opensas/2833989 to your computer and use it in GitHub Desktop.
Play framework 2 Jerkson json serializer / deserializer for Date data type
package formatters.json
import play.api.libs.json.Json.toJson
import play.api.libs.json.JsValue
import play.api.libs.json.Format
import java.util.Date
import java.text.SimpleDateFormat
object DateFormatter {
implicit object JsonDateFormatter extends Format[Option[Date]] {
val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'")
def writes(date: Option[Date]): JsValue = {
toJson(
date.map(
date => dateFormat.format(date)
).getOrElse(
""
)
)
}
def reads(j: JsValue): Option[Date] = {
try {
Some(dateFormat.parse(j.as[String]))
} catch {
case e => None
}
}
}
}
@plawler
Copy link

plawler commented Jul 6, 2014

Thank you! This works great. I had to make a couple of small changes (reads() must return a JsResult) to get it to compile with Play 2.3.x. Can't do pull requests with Gists but here is my clone - https://gist.github.com/plawler/373e1abd86789dc263bd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment