How to read date (Timestamp) from MongoDB using Java

12.5k views Asked by At

Am trying to read date field from MongoDB in below format

Formate: YYYY-MM-dd HH:mm:ss.SSSSSS

2017-01-23-10.46.07.812000 - DB2
2017-01-23T16:46:07.812Z   - Stored in MongoDB (While viewing from GUI tool)
Mon Jan 23 22:16:07 IST 2017 - Result/Reading from MongoDB

// Formatter for the input date
final DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
final ZonedDateTime dateFiledParsed = ZonedDateTime.parse(dateFiled.toString(), inputFormat);
final DateTimeFormatter outputFormat3 = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss.SSSSSS");
System.out.println(outputFormat3.format(publicationDateParsed));

Result: 2017-01-23 22:16:07.000000

In the result 2017-01-23 22:16:07.000000, instead of 000 it should be the 812 (Original value: 2017-01-23-10.46.07.812000)

Note: Using MongoDB Java driver 3.4.

Thank you in advance!

Bharathi

3

There are 3 answers

2
kevinadi On BEST ANSWER

You can use Java's SimpleDateFormat to format the date accordingly. For example, assuming you inserted the date in MongoDB using the proper ISODate type:

> db.test.find()
{
  "_id": ObjectId("597813a12dbe1d773beb11d2"),
  "date": ISODate("2017-01-23T16:46:07.812Z")
}

This code prints the correct date:

Document doc = collection.find().first();
Date date = doc.getDate("date");
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
formattedDate.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formattedDate.format(date));

Output is:

2017-01-23 16:46:07.812
0
vnapastiuk On

In my case worked the next code, when passing a date to MongoDb:

SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormat.format(date));

When retrieving it:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(dateFormat.format(date));
0
Emre Zorlu On

this 2 methods will match mongo's date format (util.Date in java)

public static String convertToString(Date date) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    dateFormat.setTimeZone(TimeZone.getTimeZone(zone));
    return dateFormat.format(date);
}

public static Date convertToDate(String strDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    dateFormat.setTimeZone(TimeZone.getTimeZone(zone));
    Date parsedDate = null;
    try {
        parsedDate = dateFormat.parse(strDate);
    } catch (ParseException e) {
        log.error(e.getMessage());
    }
    return parsedDate;

}