Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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"
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You need to use SimpleDateFormat or DateTimeFormatter classes to convert Date from one representation to another.

Refer

over 4 years ago · Santiago Trujillo Denunciar

0

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
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda