简体   繁体   English

Java Mongo日期搜索

[英]java mongo date search

We are using Java and querying MongoDB. 我们正在使用Java并查询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. 假设今天是2012年11月22日。即使我们为今天指定了$ lt,此查询也会显示21日和22日入学的学生列表。

What is the issue here? 这是什么问题?

Tha Java Date object doesn't just include the day, but also the time, accurate to the second. Tha Java Date对象不仅包括日期,还包括精确到秒的时间。 So when you create a new Date(), you get the current date with the current time. 因此,当您创建一个新的Date()时,您将获得当前日期和当前时间。 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 . 如果您的数据库包含日期而没有时间,则将其视为November 22nd 2012 00:00:00 This is less than November 22nd 2012 11:05:22 少于November 22nd 2012 11:05:22

Solution: Set the hours, minutes and seconds of toDay to 0 to exclude any dates which were today. 解决方案:将toDay的小时,分​​钟和秒设置为0,以排除今天的任何日期。

By the way : Many Java programmers consider the library jodatime far superior to Java's native date and time handling classes. 顺便说一句 :许多Java程序员认为库jodatime远远优于Java的本地日期和时间处理类。 This begins with its equivalent to java.util.Date having the less misleading name DateTime . 这从其与java.util.Date的等效项开始,该名称具有较少误导的名称DateTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM