Home > Software engineering >  moment.IsSame returning wrong result
moment.IsSame returning wrong result

Time:04-23

I am using the moment isSame which is returning false for two dates which are same,

moment(new Date('2070-07-27T21:59:59.999Z')).isSame(moment(new Date('2070-07-27T23:00:58.000Z')), 'day');

The above returns false though same day, Any help is appreciated

What alternative and accurate method can be used if this doesn't work

CodePudding user response:

I have no experience with moment, but

const d1 = new Date('2070-07-27T21:59:59.999Z');
const d2 = new Date('2070-07-27T23:00:58.000Z');
console.log(d1.getDay()); // sunday
console.log(d2.getDay()); // monday

Thus, it's not a moment issue.

Edit: Possible solution. Use the same timezone for both dates.

console.log(d1.getUTCDay() === d2.getUTCDay()); // true (same weekday)

or

console.log(
  (d1.getUTCDate() === d2.getUTCDate()) &&
  (d1.getUTCMonth() === d2.getUTCMonth()) &&
  (d1.getUTCFullYear() === d2.getUTCFullYear())
); // true (same date)

or

const moment = require('moment');

const d1 = new Date('2070-07-27T21:59:59.999Z');
const d2 = new Date('2070-07-27T23:00:58.000Z');

const isSame = moment(d1).isSame(moment(d2), 'day');
console.log(isSame); // false

const isSameFixed = moment(d1).utc().isSame(moment(d2).utc(), 'day');
console.log(isSameFixed); // true
  • Related