我正在尝试以以下格式从 MongoDB 读取日期字段
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。000000,而不是 000 应该是 812 (原始值:2017-01-23-10.46.07.812000)
注意:使用 MongoDB Java 驱动程序 3.4。
先感谢您!
Bharathi
你可以使用Java的简单日期格式 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html相应地格式化日期。例如,假设您使用以下命令在 MongoDB 中插入日期正确的 ISODate 类型 https://docs.mongodb.com/manual/core/shell-types/#date:
> 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)