春季启动:mongoDB日期比较不起作用 [英] Spring-boot: mongoDB date comparison not working
问题描述
我正在尝试预约特定日期.
I am trying to get appointments for a particular date.
因此,我通过了fromDate
和toDate
来查找该日期范围内的数据.
So I am passing fromDate
and toDate
to find data in that date range.
这是我的代码,其中查询方法正在更改传递给它的实际日期.
Here is my code, in which query method is changing the actual date passing to it.
我还已将此代码形成的查询粘贴到 spring boot 中.
I have also pasted the query formed by this code in spring boot.
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS\'Z\'");
fromDate = "2017-10-06T00:00:00.000Z";
toDate = "2017-10-07T23:00:00.000Z";
Date startDate,endDate;
startDate = dateFormatter.parse(fromDate);
endDate = dateFormatter.parse(toDate);
System.out.println(startDate);
System.out.println(endDate);
Query q = new Query().addCriteria(new Criteria().orOperator(
new Criteria().andOperator(Criteria.where("fromDate").gte(startDate),
Criteria.where("fromDate").lte(endDate)),
new Criteria().andOperator(Criteria.where("toDate").gte(startDate),
Criteria.where("toDate").lte(endDate))
));
System.out.println(startDate);
System.out.println(endDate);
System.out.println(q); //here in query m getting different date
List<Appointment> result= mongoTemplate.find(q, Appointment.class);
System.out.println(result);
当我尝试打印查询时,它会打印以下错误的json:
When I am trying to print query, it prints the following json which is wrong:
{
"$or": [
{
"$and": [
{
"fromDate": {
"$gte": {
"$date": "2017-10-05T18:30:00.000Z" //expected date 2017-10-06
}
}
},
{
"fromDate": {
"$lte": {
"$date": "2017-10-07T17:30:00.000Z"
}
}
}
]
},
{
"$and": [
{
"toDate": {
"$gte": {
"$date": "2017-10-05T18:30:00.000Z"
}
}
},
{
"toDate": {
"$lte": {
"$date": "2017-10-07T17:30:00.000Z"
}
}
}
]
}
]
}
我的预期日期是"2017-10-06T00:00:00.000Z"和"2017-10-07T23:00:00.000Z".
My expected date were "2017-10-06T00:00:00.000Z" and "2017-10-07T23:00:00.000Z".
推荐答案
使用DateFormat
解析字符串日期时,必须将时区设置为UTC.
You have to set the timezone to UTC when using DateFormat
to parse string dates.
或者,您可以在Java 8中使用Instant
.
Alternatively you can use Instant
in Java 8.
我已经展示了两个示例.
I have shown both examples.
endDate
使用dateFormatter
,时区设置为UTC
startDate
使用Instant
类似
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS\'Z\'");
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date startDate,endDate;
startDate = Date.from(Instant.parse("2017-10-06T00:00:00.000Z"));
endDate = dateFormatter.parse("2017-10-07T23:00:00.000Z");
这篇关于春季启动:mongoDB日期比较不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!