春季启动:mongoDB日期比较不起作用

编程入门 行业动态 更新时间:2024-10-24 08:24:32
本文介绍了春季启动:mongoDB日期比较不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试预约特定日期.

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日期比较不起作用

本文发布于:2023-11-22 13:06:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:春季   不起作用   日期   mongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!