Momentjs : How to prevent "Invalid date"?
Asked Answered
D

2

29

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 that and return an empty string instead.

Demolition answered 11/3, 2015 at 17:14 Comment(0)
P
41

TL;DR

If your goal is to find out whether you have a valid date, use Moment's 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 invalid.

Details

There are two very different things going on here.

First:

0000-00-00T00:00:00 is an invalid date. There's no month prior to January (which is month #1 in that format), nor a day of a month prior to day #1. So 0000-00-00 makes no sense.

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

If you use a valid date (such as your 2015-01-01T00:00:00 example), the code is fine.

Second:

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

It returns [object String] even with a valid date, so the if condition doesn't working in my case.

Of course it does: format returns a string, and you're using format to get end_date.

If you want to know if a MomentJS object has an invalid date, you can check like this:

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

If you want to know if a Date object has an invalid date:

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

...because isNaN will coerce the date to its primitive form, which is the underlying number of milliseconds since Jan 1 1970 00:00:00 GMT, and when a date has an "invalid" date, the number it contains is NaN. So isNaN(theDateObject) is true when the date is invalid.

Posting answered 11/3, 2015 at 17:26 Comment(5)
Returning "" throws errors, safe to return null.Dislocate
@Vaishak: The use case here is string formatting, "" isn't going to magically throw errors.Posting
@T.J.Crowder Could you explain me what is jsonNC that you have used here?Ky
@John: See the original question.Posting
@T.J.Crowder Thanks, actually I am facing same issue and doing like this if(moment(value_).isValid()){ return moment(value_).format('MM/DD/YYYY'); } else { return moment("");, and getting NaN when it hits else statement. Any idea what I am doing wrong?Ky
B
0

Another alternative: Custom message

moment.updateLocale("language_code", {
    invalidDate: "Custom Message"
});

Example for english with empty message:

moment.updateLocale("en", {
    invalidDate: ""
});

Reference: https://www.geeksforgeeks.org/moment-js-customize-invalid-date/

Birthstone answered 19/4, 2023 at 4:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.