2017-07-25 71 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

非常感谢! 它如预期的炒锅 –