Saurabh
Saurabh

Reputation: 940

Unable to get ISODate format result

I am using MongoCursor to iterate over a collection and to retrieve changeDate (in ISODate format). However, using mongocursor returns the data in a different format. Is it possible to retrieve the changeDate in ISODate format.

Here is the document structure and my code. Please let me know how i can retrieve date in ISODate format.

MongoCursor<Document> cursor = col.find().iterator();

        while (cursor.hasNext()) {

            Document doc = hCursor.next();
            Object changeDate = doc.getDate("ChangeDate");
            System.out.println(changeDate);
        }

changeDate is returned in the format: Wed May 05 18:46:58 EDT 2017

Structure of collection data:

{
    "_id" : ObjectId("590a253fe4b05069ea21776b"),
    "changeDate" : ISODate("2017-05-03T18:46:58.577Z"),
    "createdBy" : “abc”,
    "lastChangedBy" : “xyzzy”

}

I want the output as 2017-05-03T18:46:58.577Z. I tried using joda date but didn't find it very useful. Appreciate any help!!

Upvotes: 0

Views: 77

Answers (1)

s7vr
s7vr

Reputation: 75994

You can change Date to Instant and toString(). Uses the DateTimeFormatter.ISO_INSTANT

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT

 Date changeDate = doc.getDate("ChangeDate");
 String instant = changeDate.toInstant().toString(); // 2017-05-03T18:46:58.577Z

Upvotes: 2

Related Questions