Issue with serializing BsonDateTime to json - format discrepancy

I am having an issue with MongoDB 4.x and greater - I suspect this is due to moving from strict to relaxed mode for toJson call.

In summary when retrieving data from MongoDB and converting Document to json using document.toJson(), the conversion to date time string is inconsistent.

Conversion to ISODateTime format is different if time values is rounded to seconds or milliseconds.

For example:

  • BsonDateTime(1596118502000L) converts to {"$date": "2020-07-30T14:15:02Z"}
  • BsonDateTime(1596118502001L) converts to {"$date": "2020-07-30T14:15:02.001Z"}

In my opinion the first example should convert to {"$date": "2020-07-30T14:15:02.000Z"}

ISODateTimeFormat like Joda Time’s ISODateTimeFormatter.dateTime will fail trying to parse example 1.

Any suggestions on how to ensure output format is always the same - i.e., in example above BsonDateTime(1596118502000L) should convert to {"$date": "2020-07-30T14:15:02.000Z"}

I suspect this can be done by setting JsonWriterSettings in the document.toJson() call but this would have to done with every call with could lead to errors down the road - it would be better to be able to set a default handler to convert to json.

1 Like

I am surprised that there is no response to this post.

For now I have implemented a implicit class to provide extension asJson to Document class.

object DocumentHelpers {
  class DTC extends Converter[LongJ] {
    val fmt = ISODateTimeFormat.dateTime().withZoneUTC()

    override def convert(value: LongJ, writer: StrictJsonWriter): Unit = {
      val str = fmt.print(value)
      writer.writeString(str)
    }
  }
  private val settings: JsonWriterSettings = JsonWriterSettings
    .builder()
    .dateTimeConverter(new DTC)
    .build()

  implicit class DocToJson(document: Document) {
    def asJson(): String = document.toJson(settings)
  }
}

This allows better control of serial format using asJson than toJson which is inconsistent in output format.

I have also found that setting collection’s document class to JsonObject and providing a Codec for DateTime gives me control and consistency of date/time output.

1 Like