Skip to content

Instantly share code, notes, and snippets.

@borice
Created March 9, 2019 01:40
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/860c3128f892080c621194b0b07f84c9 to your computer and use it in GitHub Desktop.
Save borice/860c3128f892080c621194b0b07f84c9 to your computer and use it in GitHub Desktop.
Converts LocalDate and Instant from java.time to/from BSONDateTime
import java.time.{Instant, LocalDate, ZoneOffset}
import reactivemongo.bson._
object BsonImplicits {
implicit object LocalDateBsonReaderWriter extends BSONReader[BSONValue, LocalDate] with BSONWriter[LocalDate, BSONDateTime] {
override def read(bson: BSONValue): LocalDate = bson match {
case BSONDateTime(millis) => Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate
case BSONLong(millis) => Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate
case _ => throw new IllegalArgumentException(s"Cannot convert $bson to java.time.LocalDate")
}
override def write(date: LocalDate): BSONDateTime =
BSONDateTime(date.atStartOfDay().atZone(ZoneOffset.UTC).toInstant.toEpochMilli)
}
implicit object InstantBsonReaderWriter extends BSONReader[BSONValue, Instant] with BSONWriter[Instant, BSONDateTime] {
override def read(bson: BSONValue): Instant = bson match {
case BSONDateTime(millis) => Instant.ofEpochMilli(millis)
case BSONLong(millis) => Instant.ofEpochMilli(millis)
case _ => throw new IllegalArgumentException(s"Cannot convert $bson to java.time.Instant")
}
override def write(instant: Instant): BSONDateTime = BSONDateTime(instant.toEpochMilli)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment