Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 Respostas
Responde à pergunta

0

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

Refer

over 4 years ago · Santiago Trujillo Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda