Search code examples
javaspringspring-bootdatetimespring-mongodb

I am trying to convert some Strings I received from my mongodb collection into a java date object. But I can't seem to find a pattern that works


I want to convert values from my mongoDB format into a java Date object(LocalDateTime would also be fine). But I can't find the pattern that does the job.

My 'lastupdated' value inside the mongodb collection is like this. lastupdated : "2015-08-26 00:03:50.133000000"

I have successfully created a connection but I am getting an error converting it from a string to a date. This is what the error I am being shown. Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2015-08-31 00:41:20.670000000'

I am also struggling to convert this kind of String with key 'release'.

release : '1893-05-09T00:00:00.000+00:00;

I have applied the DateTimeFormat annotation which has usually worked for me in Spring as shown below.

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSZ")
    private Date lastupdated;

I have also tried other similar variations such as

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.S")
    private Date lastupdated;

For my other String, I tried this.

    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    private String released;`

I have looked through the pattern documentation linked here. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html#patterns

I am not able find the right format I believe, or perhaps there is a better way of doing this?


Solution

  • So it turns out that if a date that is saved as a type String inside MongoDB, the default mapper cannot read it as a Java Date or LocalDateTime object. It has be mapped to a java String (unless you create the mapper function yourself). I could be wrong but that is the conclusion I have come to.