Created
March 9, 2019 01:40
-
-
Save borice/860c3128f892080c621194b0b07f84c9 to your computer and use it in GitHub Desktop.
Converts LocalDate and Instant from java.time to/from BSONDateTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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