0

I have the following request, two string of date in format "yyyy-MM-dd'T'hh:mm:ss"

{  
    "dataS": "2021-07-22T03:00:00Z",
    "dataE": "2021-07-23T03:00:00Z",
}

and I need to transform this value into a Date format to build the following query

Query query = new Query();
query.addCriteria(Criteria.where("date").gte(dataS).lte(dataE));

The format of the field "date" in MongoDB is ISODate like that: { "date" : ISODate("2019-04-13T03:00:00.000+0000")}

I try 2 approachs

  1. Using the String value, I have the following query. This query does not work.

    Query: { "date" : { "$gte" : "2021-07-22T03:00:00" , "$lte" :"2021-07-23T03:00:00"}, "isDeleted" : false }, Fields: { }, Sort: { }

  2. Transforming the String to the Data format, as follows I get only the TimeStamp

    DateFormat originalFormatData = new SimpleDateFormat( "yyyy-MM-dd'T'hh:mm:ss", Locale.ENGLISH); query.addCriteria(Criteria.where("date").gte(originalFormatData.parse(dataS)).lte(originalFormatData.parse(dataE)));

    Result: Query: { "date" : { "$gte" : { "$date" : 1626933600000 }, "$lte" : { "$date" : 1627019999000 } }, "isDeleted" : false }, Fields: { }, Sort: { }

The final result that I would like and that works for the query would be this:

 Query: { "date" : { "$gte" : { "$date" : "2021-07-22T03:00:00" }, "$lte" : { "$date" : "2021-07-23T03:00:00" } }, "isDeleted" : false }, Fields: { }, Sort: { }

Can someone help me with parse ?

1 Answers1

0

DateFormat#parse(String source) actually produces a Date object from a String. The DateFormat#format(Date date) should be used to format the date into a String representation.

parse from Date Format's javadoc:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

format from Date Format's javadoc:

Formats a Date into a date/time string.

I think you need to format a Date into the desired format (thus use the format method).

I'm not seeing your request class code, but an idea: you can receive the dataS and dataE properties as Dates, instead of strings. And then call DateFormat#format(Date date) to get them as Strings in the desired format.

But before you go too far down that route, have a look at this answers:

Spring data mongodb query converts String to ObjectId automatically

Jackson Mapper Serialize/Deserialize ObjectId

I'm guessing that this can be solved by writing your own Jackson Serializer.

Matheus
  • 3,058
  • 7
  • 16
  • 37