Home > database >  How to compare two date in node js?
How to compare two date in node js?

Time:04-10

Compare dates from an array object with the current date. the current date is taken from MongoDB.

{"specialData": [
        {
            "content": {
                "dateAdded": "2017-12-26T22:21:37 00:00"
            }
        },
        {
            "content": {
                "dateAdded": "2018-01-12T22:21:37 00:00"
            }
        }
]
}

compare the content.dateAdded from the array object with the current date coming from MongoDB. current date coming from catalogue.metaData.lastUpdatedDate

let result = _.find(rokuFeeds.tvSpecials, function (n) {
      if (new Date(n.content.dateAdded) < new Date(catalogue.metaData.lastUpdatedDate)) {
        return true;
      }
    });

I'm trying like this

CodePudding user response:

You can use new Date(obj.specialData[0].content.dateAdded); to convert string to date object.

const obj = {
  "specialData": [{
    "content": {
      "dateAdded": "2017-12-26T22:21:37 00:00"
    }
  },
  {
    "content": {
      "dateAdded": "2018-01-12T22:21:37 00:00"
    }
  }]
}
const d1 = new Date(obj.specialData[0].content.dateAdded);
const d2 = new Date(obj.specialData[1].content.dateAdded);

console.log('d1 is:', d1.toLocaleString());
console.log('d2 is:', d2.toLocaleString());

console.log('d1 - d2: ', d1 - d2, 'seconds');

output

desc value
d1 26/12/2017, 23:21:37
d2 12/01/2018, 23:21:37
d1 - d2 -1468800000 seconds

CodePudding user response:

You can compare dates by using getTime() method.

const obj = {
  "specialData": [{
    "content": {
      "dateAdded": "2017-12-26T22:21:37 00:00"
    }
  },
  {
    "content": {
      "dateAdded": "2018-01-12T22:21:37 00:00"
    }
  }]
}

const d1 = new Date(obj.specialData[0].content.dateAdded).getTime();
const d2 = new Date(obj.specialData[1].content.dateAdded).getTime();

Now simply compare them, using comparison operators > < >= <=

d1 > d2;  //false
d1 < d2;  //true
d1 >= d2; //false
d1 <= d2; //true
  • Related