comparing dates in mongodb

寵の児 提交于 2019-12-31 04:31:11

问题


A Meteor server code updates a Mongodb collection, dateField has value looking like this
ISODate("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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!