Home > other >  Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment&
Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment&

Time:11-23

I want to compare last 30 mins data and display in UI. Datetime needs be UTC. I tried using Moment but i am getting error

Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'.

Below is my code :

  let d = moment();
      let d_utc = moment.utc();
      var customDate = new Date();
      d_utc.minutes(-30);  

      filteredData = filteredData.filter((category) => {
        return category.uploaded_time  > d_utc;
      });

CodePudding user response:

If you wish to compare a Date to an instance of a Moment with a Date, you need to convert them both to the same date.

You can call .toDate() to convert a moment to a Date or moment(date) to convert a Date to a Moment.

return category.uploaded_time > d_utc.toDate()

JavaScript doesn't have operator overrides, so the safest way to compare Moments is using diff:

return moment(category.uploaded_time).diff(d_utc) > 0

CodePudding user response:

At the documentation in get set section you can compare the seconds

Examplet in documentation

moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);

Your code should be

 let d_utc = moment.utc();
       let d_utc = moment.utc().minutes(-30).valueOf();

      filteredData = filteredData.filter((category) => {
        return category.uploaded_time.getUTCSeconds()  > d_utc;
      });

Also there is a query section you can check it

  • Related