Home > other >  Java Date to MongoDB date with Gson
Java Date to MongoDB date with Gson

Time:02-04

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:

Date.now() -> "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

And I was wondering how I could do to create an object conforming to Gson's serialization?

For example:

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

CodePudding user response:

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"

CodePudding user response:

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

Refer

  •  Tags:  
  • Related