Moments: How to prevent "Invalid date"?

I have the following code:

var fomattedDate = moment(myDate).format("L"); 

Sometimes moment(myDate).format("L") returns "Invalid date", I want to know if there is a way to prevent this and return an empty string.

+8
javascript momentjs invalidate
source share
1 answer

TL; DR

If your goal is to find out if you have a valid date, use Moment isValid :

 var end_date_moment, end_date; jsonNC.end_date = jsonNC.end_date.replace(" ", "T"); end_date_moment = moment(jsonNC.end_date); end_date = end_date_moment.isValid() ? end_date_moment.format("L") : ""; 

... which will use "" for the end_date string if the date is not valid.

More details

Two very different things happen here.

At first:

0000-00-00T00:00:00 is an invalid date. There is no month until January (month 1 in this format), no day of the month until day No. 1. Therefore, 0000-00-00 does not make sense.

0000-01-01T00:00:00 will be valid - and moment("0000-01-01T00:00:00").format("L") happily returns "01/01/0000" for it.

If you use a valid date (for example, example 2015-01-01T00:00:00 ), the code is OK.

Secondly:

 console.log(Object.prototype.toString.call(end_date)); 

It returns a [String object] even with a valid date, so the if condition does not work in my case.

Of course: format returns a string, and you use format to get end_date .

If you want to find out if the MomentJS object has an invalid date, you can check the following:

 if (theMomentObject.isValid()) { // It has as valid date } else { // It doesn't } 

If you want to find out if the Date object has an invalid date:

 if (!isNaN(theDateObject)) { // It has as valid date } else { // It doesn't } 

... because isNaN will force the date to its primitive form, which is the base number of milliseconds from January 1, 1970, 00:00:00 GMT, and when the date has an "invalid" date, it contains NaN . Therefore, isNaN(theDateObject) is true if the date is invalid.

+13
source share

All Articles