java mongodb 时间,如何使用Java从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

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值