1

We are using Java and querying MongoDB. Want to get the records from a previous day. For example, we want to get all the students that enrolled yesterday. Here is the query that we use,

Date toDay = new Date();            
Date twoDaysBack  = Util.twoDaysBack(toDay);
query.put("enroldate", new BasicDBObject("$gt", twoDaysBack).append("$lt", toDay));

Say, if today is 22nd Nov, 2012. This query shows the list of students enrolled on 21st as well as 22nd even though we have specified $lt for today.

What is the issue here?

4

1 に答える 1

1

Tha Java Date object doesn't just include the day, but also the time, accurate to the second. So when you create a new Date(), you get the current date with the current time. Any earlier date today is less than it. When your database includes the date without a time, it is treated as November 22nd 2012 00:00:00. This is less than November 22nd 2012 11:05:22

Solution: Set the hours, minutes and seconds of toDay to 0 to exclude any dates which were today.

By the way: Many Java programmers consider the library jodatime far superior to Java's native date and time handling classes. This begins with its equivalent to java.util.Date having the less misleading name DateTime.

于 2012-11-22T10:04:13.887 に答える