Home > Software engineering >  How to format a moment date and compare with another moment date
How to format a moment date and compare with another moment date

Time:05-12

I am trying to format a moment date and compare. I know the below is not valid. How can i do both at the same time?

moment('value'). format('MM/DD/YYYY). isSame ( moment ('value). format('MM/DD/YYYT')

CodePudding user response:

just compare them?

var date = moment('04/22/2022').format('MM/DD/YYYY')
var today = moment(new Date()).format('MM/DD/YYYY')

if (today > date) {
   // date is from the past
} else {
   // date is from the future
}

edit to show using isSame method:

moment(moment(new Date("may 11 2022")).format("MM/DD/YYYY")).isSame("05/11/2022"); // true

CodePudding user response:

you can use moment().diff to compare.

Check this out: https://momentjs.com/docs/#/displaying/difference/

var a = moment();
var b = moment().add(1, 'seconds');
a.diff(b) // -1000, it is negative, it means a is smaller than b
b.diff(a) // 1000, it is positive which means b is bigger than a.

CodePudding user response:

Make a note, when you are using any momentjs queries than you should make sure that the datetime is in proper ISO fomat , if it is not than you will get the follwing error.

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.

You should be able to compare them directly.


var date = moment("2013-03-24")
var now = moment();

if (now > date) {
   // date is past
} else {
   // date is future
}
  • Related