MongoDB中的日期:将Date对象插入Mongo数据库时,该日期比其本身早1天 [英] date in MongoDB: when inserting Date objects into Mongo database, the date becomes 1 day earlier than itself

查看:259
本文介绍了MongoDB中的日期:将Date对象插入Mongo数据库时,该日期比其本身早1天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的日期字符串格式如下: 2012年1月2日 使用Instant.parse()方法后,即时实例的日期变为2012年1月1日,该日期早1天,为什么?如果原始日期字符串为2012年1月1日,则Instant的日期为2011年12月31日.

My date string format is like this: Jan 2, 2012 After the Instant.parse() method, instant instance becomes the date of Jan 1, 2012, which is 1 day earlier, why? If the original date string is jan 1, 2012, the Instant will be the date of Dec 31, 2011.

String dateString="Jan 1, 2012";
Instant instant = Instant.parse(dateString, new DateTimeFormatterBuilder()
.appendMonthOfYearShortText()
.appendLiteral(" ")
.appendDayOfMonth(1)
.appendLiteral(", ")
.appendYear(4, 4)
.toFormatter());

DateTime dateTime = new DateTime(instant);
Date date = new Date(dateTime.getMillis());

document.append("time", new Date(dateTime.getMillis()));
tagsDbCollection.insert(document);


我正在使用MongoDB存储这些日期.我已经测试过了,它显示了格式化日期字符串->即时时没有错误. 但是,当我将此Date类型的对象插入MongoDB时,MongoDB中的日期字符串会提前1天.


I'm using MongoDB to store these dates. I've tested and it shows when formatting date string->instant there's no mistake. But when I insert this Date type object into MongoDB, the date string in the MongoDB becomes 1 day earlier., why?

在MongoDB中:

 /* 0 */
    {
      "_id" : ObjectId("50221a40da74d74053abb445"),
      "time" : ISODate("2011-12-31T14:00:00Z")
    }

推荐答案

final String dateString = "Jan 2, 2012";
final DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendMonthOfYearShortText().appendLiteral(" ").appendDayOfMonth(1).appendLiteral(", ").appendYear(4, 4).toFormatter();
final DateTime jodaDate = dtf.parseDateTime(dateString);
System.out.println(jodaDate);
final Date javaDate = new Date(jodaDate.getMillis());
System.out.println(javaDate); 

输出为

2012-01-02T00:00:00.000+02:00
Mon Jan 02 00:00:00 EET 2012  

下一步:

final String dateString = "Jan 1, 2012";

输出为:

2012-01-01T00:00:00.000+02:00
Sun Jan 01 00:00:00 EET 2012

这篇关于MongoDB中的日期:将Date对象插入Mongo数据库时,该日期比其本身早1天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆