Skip to content

Instantly share code, notes, and snippets.

@opensas
Created May 30, 2012 05:53
Show Gist options
  • Select an option

  • Save opensas/2833989 to your computer and use it in GitHub Desktop.

Select an option

Save opensas/2833989 to your computer and use it in GitHub Desktop.

Revisions

  1. opensas created this gist May 30, 2012.
    36 changes: 36 additions & 0 deletions DateFormatter.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    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
    }
    }

    }

    }