2012-08-05 95 views
8

我的日期字符串格式是这样的:2012年1月2日 在Instant.parse()方法之后,即时实例变为2012年1月1日的日期是1天前,为什么?如果原来的日期字符串为2012年1月1日,即时将是12月31日,2011年在MongoDB中的日期:当将日期对象插入Mongo数据库时,日期比它自己早1天

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天。为什么?

在MongoDB中:

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

您是否尝试添加时区组件?它可能与你的本地和日期抵消你的时区的东西。 – 2012-08-07 21:22:50

回答

1
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 
+0

感谢您的回复。是的,日期字符串 - >即时没有错。当我将这些日期插入MongoDB时,出现了这个问题。仍然不知道为什么...我已经更新了这个问题。 – 2012-08-08 08:04:12

+0

可能你有TimeZone -10。因此节省了前一天下午2点的时间。当我使用MongoDB时,我将日期保存为毫秒内的long值 – Ilya 2012-08-08 11:31:17

+0

是的,它是一个时区问题。我在澳大利亚布里斯班。这是UTC + 10。 [本页](https://jira.mongodb。org/browse/CSHARP-185)说:“MongoDB以UTC来存储所有日期时间,当你存储在数据库中时,你提供的任何本地时间都被转换为UTC”。当我通过Java API查询来自MongoDB的日期时,我发现插入后日期会再次转换为本地时间。所以现在好了。谢谢。 – 2012-08-10 01:54:52

1

Mongo自Unix时代开始存储以毫秒为单位的日期。

请参见:http://www.mongodb.org/display/DOCS/Dates

所以你不要有任何时区。但是,如果您使用控制台,则.js分析器会将UTC日期转换为您当前的系统时区设置。

您可以测试:

  • 一些日期数据创建一个实体。
  • 然后通过控制台查询它。 (使用字符串())
  • 然后退出控制台并重新配置系统时区(于Debian/Ubuntu:sudo的dpkg的 - 重新配置的tzdata)
  • 然后再次进入控制台和查询您的旧数据=>你会得到相同的UTC但不同的toString()输出
0

你可以检查UTC时区,基本上蒙戈服务器的运行依赖于UTC时区

的SimpleDateFormat格式=新的SimpleDateFormat( “DD/MM/YYYY”); format.setTimeZone(TimeZone.getTimeZone(“UTC”));