Skip to content

Instantly share code, notes, and snippets.

@borice
Created March 9, 2019 01:41
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 borice/5aff731988a54b978ed9ab298361b501 to your computer and use it in GitHub Desktop.
Save borice/5aff731988a54b978ed9ab298361b501 to your computer and use it in GitHub Desktop.
Converts LocalDate and Instant from java.time to/from Play JSON for MongoDB use
import java.time.{Instant, LocalDate, ZoneOffset}
import play.api.libs.json._
object JsonImplicits {
implicit object LocalDateMongoJsonReaderWriter extends Reads[LocalDate] with Writes[LocalDate] {
override def reads(json: JsValue): JsResult[LocalDate] =
(json \ "$date").validate[Long].map(Instant.ofEpochMilli(_).atZone(ZoneOffset.UTC).toLocalDate)
override def writes(date: LocalDate): JsValue =
Json.obj("$date" -> date.atStartOfDay().atZone(ZoneOffset.UTC).toInstant.toEpochMilli)
}
implicit object InstantMongoJsonReaderWriter extends Reads[Instant] with Writes[Instant] {
override def reads(json: JsValue): JsResult[Instant] =
(json \ "$date").validate[Long].map(Instant.ofEpochMilli)
override def writes(instant: Instant): JsValue =
Json.obj("$date" -> instant.toEpochMilli)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment