Search code examples
javajsonmongodblocaldatedate

Java LocalDate - Time gets appended onto date when saving in MongoDB?


I have the following Java Entity:

public class Round {

    private ObjectId _id;

    @NotEmpty
    @Getter
    @Setter
    @Accessors(fluent = true)
    @JsonProperty("userId")
    private String userId;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    @Getter
    @Setter
    @Accessors(fluent = true)
    @JsonProperty("date")
    private LocalDate date;

    //other fields

}

When I do a POST to my Spring Boot REST web app with JSON Body:

{
  "userId": "user3",
  "date": "20-01-2020"
}

The date is persisted in Mongo as follows:

2020-01-20T00:00:00.000+00:00

How can I get the date to persist as simply:

20-01-2020

Solution

  • It's not Java problem, MongoDB uses Date format similar to JavaScript Date format. If you want to save just dd-MM-YYYY you may want to change your column type to String. If it's not possible then you need to rewrite your serializer to return String representation of date (and of course rewrite deserializer to parse that string into LocalDate