How to read date (Timestamp) from MongoDB using Java

Bharathiraja S picture Bharathiraja S · Jul 25, 2017 · Viewed 9.2k times · Source

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

Answer

kevinadi picture kevinadi · Jul 26, 2017

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