问题
A Meteor server code updates a Mongodb collection, dateField
has value looking like thisISODate("2016-11-19T00:00:00Z")
The client selects a dateStart
and dateFinish
, look like this
$('input[name="startDateStr"]').val() // => "2016-11-19"
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]));
}
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?
回答1:
new Date(year, month, date) variant will have the date in current system time zone.
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.
Considering user inputs date as UTC. You'll just need to parse the date explicitly as UTC.
Try
new Date(Date.UTC(2016, 11, 19, 0, 0, 0, 0)
and pass this to the query.
来源:https://stackoverflow.com/questions/40690827/comparing-dates-in-mongodb