score:16

Accepted answer

Looking at the source code for the existing handlers, you could try to create an implicit conversion like this (not tested):

import org.joda.time.DateTime

implicit object BSONDateTimeHandler extends BSONHandler[BSONDateTime, DateTime] {
  def read(time: BSONDateTime) = new DateTime(time.value)
  def write(jdtime: DateTime) = BSONDateTime(jdtime.getMillis)
}

score:0

For version 1.0.x

  implicit object DateTimeReader extends BSONReader[DateTime] {
    def readTry(bson: BSONValue): Try[DateTime] =  bson match {
      case time: BSONDateTime => Success(new DateTime(time.value))
      case _ => Failure(new IllegalArgumentException())
    }
  }

  implicit object DateTimeWriter extends BSONWriter[DateTime]{
    override def writeTry(t: DateTime): Try[BSONValue] = Try{
      BSONDateTime(t.getMillis)
    }
  }

or with val

  implicit val dateTimeReader: BSONReader[DateTime] = BSONReader[DateTime]{
    case  t: BSONDateTime => new DateTime(t.value)
  }

  implicit val dateTimeWriter: BSONWriter[DateTime] = BSONWriter[DateTime]{ time =>
    BSONDateTime(time.getMillis)
  }

score:2

Another approach is to use new BSONReader & BSONWriter(having 2 type parameters in 0.9):

implicit object DatetimeReader extends BSONReader[BSONDateTime, DateTime]{
    def read(bson: BSONDateTime): DateTime = new DateTime(bson.value)
}

implicit object DatetimeWriter extends BSONWriter[DateTime, BSONDateTime]{
    def write(t: DateTime): BSONDateTime = BSONDateTime(t.getMillis)
}

Related Query

More Query from same tag