-1

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?

  • 1
    You want to avoid using `Date`. It’s a legacy class that was finally supplanted nearly 10 years ago because it was poorly designed. Use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). – Ole V.V. Mar 21 '23 at 07:55
  • 1
    `LocalDateTime` is the wrong Java type as well. That type cannot represent a point on the timeline as it has only a date with time but no time zone nor offset-from-UTC. – Basil Bourque Mar 26 '23 at 00:59
  • 1
    Never put `Z` inside quotes in a date-time formatting pattern. You are discarding valuable information: an offset of zero hours-minutes-seconds. – Basil Bourque Mar 26 '23 at 00:59
  • This question is convoluted and unclear. I suggest you show an utterly simple but complete example of storing a date-time value, and of retrieving that date-time value. This question is also likely a duplicate of others. – Basil Bourque Mar 26 '23 at 01:00

1 Answers1

0

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.