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:

JavaScript

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

Affected code

JavaScript
JavaScript

Question

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

For example:

JavaScript

Advertisement

Answer

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

Code:

JavaScript

Output:

JavaScript

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:

JavaScript

On my machine it is:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement