比较日期在mongodb [英] comparing dates in mongodb
问题描述
流星服务器代码更新Mongodb集合, dateField
具有如下值:
ISODate(2016-11 -19T00:00:00Z)
A Meteor server code updates a Mongodb collection, dateField
has value looking like this
ISODate("2016-11-19T00:00:00Z")
客户端选择一个 dateStart
code> dateFinish ,看起来像这样
$('input [name =startDateStr]')val()// =>2016-11- 19
The client selects a dateStart
and dateFinish
, look like this
$('input[name="startDateStr"]').val() // => "2016-11-19"
所以我转换用户条目,以便我可以使用它来获取文档与 dateField
匹配下面的mongodb查询;
So I convert the user entry so that I can use it to get the documents with the dateField
matching the below mongodb query;
dateToISO: (date) => { // date format in YYYY-MM-DD
const dArr = date.split('-');
return new Date(parseInt(dArr[0]), parseInt(dArr[1]) - 1, parseInt(dArr[2]));
}
然后将结果呈现给具有日期的用户在formate DD / MM / YYYY
And then present the results to the user with the date in the formate DD/MM/YYYY
let start = utility.dateToISO(dict.get('inquiryStartDate'));
let end = utility.dateToISO(dict.get('inquiryEndDate'));
////Both of the above prints: Sat Nov 19 2016 00:00:00 GMT+1100 (AEDT)
return myCol.find({
date: {
$gte: start,
$lte: end
}
}, {
transform: function(doc) {
doc.date = moment(doc.date).format('DD/MM/YYYY');
return doc;
}
});
代码无法返回任何文档事件,尽管有些存在。任何想法为什么和如何解决?
The code fails to return any documents event though some exist. Any idea why and how to fix it?
推荐答案
新日期(年,月,日)变种将有日期在当前系统时区。
new Date(year, month, date) variant will have the date in current system time zone.
比较不返回任何结果的原因是当您在本地系统区域中传递日期时,流星将从本地datetime转换为UTC datetime作为Mongo DB数据时间在UTC时间。所以您的输入日期从2016年11月19日星期六00:00:00 GMT + 1100(AEDT)到2016年11月18日星期一01:00:00 UTC。
The reason you comparison doesn't return any results is when you pass the date in your local system zone , the meteor does a conversion from local datetime to UTC datetime as Mongo DB datetimes are in UTC time. So your input date changes from Sat Nov 19 2016 00:00:00 GMT+1100 (AEDT) to Fri Nov 18, 2016 01:00:00 UTC.
用户输入日期为UTC。你只需要明确地解析为UTC。
Considering user inputs date as UTC. You'll just need to parse the date explicitly as UTC.
尝试
new Date(Date.UTC(2016, 11, 19, 0, 0, 0, 0)
并将其传递给查询。
这篇关于比较日期在mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!