skip to Main Content

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

2

Answers


  1. 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
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search