-1

how can we convert string with format mm/dd/yyyy to Date ISO format, which can be passed as an input to mongo db Query using java ?

eg: Input format for string is 11/30/2022 which needs to converted into ISODate("2022-11-30T00:00:00.000+0000")

Update:

Added the below code snippet which generated the date and passed to the query as shown in the below image and i'm using mongoTemplate to execute the query.

mongoTemplate.find(query, Packet.class); enter image description here

When the codeis executed it returns empty even though there is a record for the given input.

Ran this directly in mongodb client and it doesn't return anything. enter image description here

But when I update the query to in mongodb client, by adding ISODate() it returns the correct response. enter image description here

So wondering where i'm making a mistake!!

Karthik
  • 145
  • 1
  • 2
  • 12
  • 2
    `LocalDate.parse("11/30/2022", DateTimeFormatter.ofPattern("MM/dd/uuuu")).atStartOfDay(ZoneOffset.UTC).toOffsetDateTime()` – Arvind Kumar Avinash Nov 30 '22 at 17:03
  • @ArvindKumarAvinash If MongoDB doesn’t accept an `OffsetDateTime`, we may need to format it into a string without colon in the UTC offset. – Ole V.V. Nov 30 '22 at 17:39
  • Related (not the same, I think): [MongoDB ISODate field search using Java](https://stackoverflow.com/questions/41847667/mongodb-isodate-field-search-using-java). Also without knowing MongoDB, this seems mighty helpful in my eyes: [Using Dates in CRUD Operations in MongoDB](https://www.baeldung.com/mongodb-java-date-operations). – Ole V.V. Nov 30 '22 at 17:43
  • 2
    [*Using OffsetDateTime with Spring Boot and MongoDB*](https://bootify.io/mongodb/offset-date-time-with-spring-boot-mongodb.html) – Basil Bourque Nov 30 '22 at 18:11

1 Answers1

3

Parse the given date string into a LocalDate and then use LocalDate#atStartOfDay(ZoneId zone) with ZoneOffset.UTC to convert it into an OffsetDateTime. Subsequently, format the obtained OffsetDateTime into the desired string.

Demo:

import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM/dd/uuuu");
        OffsetDateTime odt = LocalDate.parse("11/30/2022", parser).atStartOfDay(ZoneOffset.UTC).toOffsetDateTime();
        System.out.println(odt);

        // Custom format
        String formatted = odt.format( DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx"));
        System.out.println(formatted);
    }
}

Output:

2022-11-30T00:00Z
2022-11-30T00:00:00.000+0000

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110