date in MongoDB: when inserting Date objects into Mongo database, the date becomes 1 day earlier than itself

时光怂恿深爱的人放手 提交于 2019-12-01 17:06:55
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); 

Output is

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

Next for:

final String dateString = "Jan 1, 2012";

output is:

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

Mongo stores its Dates in milliseconds since the Unix epoch.

See: http://www.mongodb.org/display/DOCS/Dates

So you dont have any time zone. But, if you use the console the .js parser is converting the UTC Dates into your current system time zone settings.

You can test that:

  • Create an Entity with some Date data.
  • then querying it via the console. (use String())
  • then exit the console and reconfigure the system time zone (debian/ubuntu: sudo dpkg-reconfigure tzdata )
  • then enter the console again and query your old data => you get the same UTC but different toString() outputs
Nifras Nipy

You could check the UTC time zone, basically mongo server running depending on UTC time zone

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); format.setTimeZone(TimeZone.getTimeZone("UTC"));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!