Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isSame() function in moment.js or Date Validation

People also ask

How do I check if a moment has a valid date?

isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.

How do you know if two dates are equal in moment?

js isSame() Function. You can check whether a given date is equal to another date in Moment. js using isSame() function that checks if a moment is the same as another moment.

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.


Docs - Is Same

Check if a moment is the same as another moment.

moment('2010-10-20').isSame('2010-10-20'); // true

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isSame('2009-12-31', 'year'); // false
moment('2010-10-20').isSame('2010-01-01', 'year'); // true
moment('2010-10-20').isSame('2010-12-31', 'year'); // true
moment('2010-10-20').isSame('2011-01-01', 'year'); // false

Your code

var x=moment("28-02-1999","DD-MM-YYYY"); // working
x.isSame("28-02-1999"); // comparing x to an unrecognizable string

If you try moment("28-02-1999"), you get an invalid date. So comparing x to an invalid date string returns false.

To fix it, either use the default date format (ISO 8601):

var x = moment("28-02-1999","DD-MM-YYYY");
x.isSame("1999-02-28"); // YYYY-MM-DD

Or pass isSame a moment object.

var x = moment("28-02-1999","DD-MM-YYYY");
x.isSame( moment("28-02-1999","DD-MM-YYYY") );