如何使用Java从MongoDB中读取日期(时间戳) [英] How to read date (Timestamp) from MongoDB using Java
本文介绍了如何使用Java从MongoDB中读取日期(时间戳)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试以以下格式从MongoDB中读取日期字段
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
结果为2017-01-23 22:16:07. 000 000,而不是000,应该是812(原始值:2017-01-23-10.46.07.812000)
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)
注意:使用MongoDB Java驱动程序3.4.
Note: Using MongoDB Java driver 3.4.
提前谢谢!
巴拉提
推荐答案
您可以使用Java的正确的ISODate类型在MongoDB中插入了日期:
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));
输出为:
2017-01-23 16:46:07.812
这篇关于如何使用Java从MongoDB中读取日期(时间戳)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文