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?

2
  • 1
    What is the issue here? The issue is that you didn't include what is the error message, or the problem you receive when running the code... Commented Nov 22, 2012 at 9:58
  • 2
    The issue here is that he wants the data from yesterday, but he receives the data from today as well. I think he explained it adequately. Commented Nov 22, 2012 at 10:07

1 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.