Skip to content

Instantly share code, notes, and snippets.

@plawler
Forked from opensas/DateFormatter.scala
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plawler/373e1abd86789dc263bd to your computer and use it in GitHub Desktop.
Save plawler/373e1abd86789dc263bd to your computer and use it in GitHub Desktop.
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): JsResult[Option[Date]] = {
try {
JsSuccess(Some(dateFormat.parse(j.as[String])))
} catch {
case e: Exception => JsSuccess(None)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment