Skip to content
Advertisement

Java Date to MongoDB date with Gson

Introduction

I am currently working on a project that regularly saves several java objects to a MongoDB database. This object contains a Date.

Problem

The conversion of java Date to Json Mongo give this:

new Date() -> "Jan 27, 2022, 2:47:24 AM"

But this format does not conform with MongoDB Date. MongoDB is considered as a string instead of a Date.

Affected code

 public record DatedPuzzle(Date date, Puzzle puzzle) { 
 } 
List<InsertOneModel<Document>> bulkWrites = puzzles.parallelStream() 
         .map(puzzle -> new InsertOneModel<>(Document.parse(gson.toJson(puzzle)))) 
         .toList(); 

Question

How to create an object conforming to Gson’s serialization?

For example:

new Date() -convert with Gson-> "2022-01-27T01:47:24.000+00:00"

Advertisement

Answer

You could create a Gson object not directly but using GsonBuilder and with some configuration, you will achieve the desired result.

Code:

public static void main(String[] args) {
    Date date = new Date();
    System.out.println(date);

    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSXXX")
            .create();

    System.out.println(gson.toJson(date));
}

Output:

Thu Feb 03 23:18:18 EET 2022
"2022-02-03T11:18:18.650+02:00"

UPDATE:

The disclaimer of the pattern is following:

  • y Year (e.g. 12 or 2012)
  • M Month in a year
  • d Day in a month
  • h Hour of the day, 1-12
  • m Minute in an hour, 0-59
  • s Second in a minute, 0-59
  • S Millisecond in second, 0-999
  • ' Escape for text delimiter
  • X – ISO 8601 time zone (-08; -0800; -08:00)

z – General time zone (Pacific Standard Time; PST; GMT-08:00)
Z – RFC 822 time zone (-0800)

Added some additional codes for a much better understanding of the output on Github.
You could check the locale which is used there simply:

System.out.println(Locale.getDefault());

On my machine it is:

en_US
Advertisement