2017-07-25 45 views
0

想讀從MongoDB的日期字段在下面的格式如何使用Java

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 

在結果2017年1月23日22時16分07秒讀取從MongoDB的日期(時間戳)。 000,而不是000它應該是812(原始值:2017-01-23-10.46.07.812000)

注意:使用MongoDB Java驅動程序3.4。

預先感謝您!

Bharathi

+0

如果它實際上是一個BSON日期(這意味着它在'mongo' shell中查看時顯示爲'ISODate'),那麼解析爲java.util.Date的任何東西都是查詢的預期輸入格式。如果您發送任何其他格式,那麼它將不會匹配。除非您瞭解轉換過程,否則請注意使用UTC值而不是本地時間。 –

+0

什麼是'dateFiled'或'dateFiled.toString()'的字符串輸出? – Seelenvirtuose

+0

@Seelenvirtuose - dateFiled是「日期dateFiled =」某日期「 –

回答

3

您可以使用Java的SimpleDateFormat相應格式的日期。例如,假設你插入MongoDB中的日期使用the proper ISODate type

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

此代碼打印正確的日期:

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)); 

輸出是:

2017-01-23 16:46:07.812 
+0

非常感謝! 它如預期的炒鍋 –