Tyler Tyler - 3 months ago 16x
Java Question

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

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()
.appendLiteral(" ")
.appendLiteral(", ")
.appendYear(4, 4)

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

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

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?

In 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);
final Date javaDate = new Date(jodaDate.getMillis());

Output is

Mon Jan 02 00:00:00 EET 2012  

Next for:

final String dateString = "Jan 1, 2012";

output is:

Sun Jan 01 00:00:00 EET 2012