问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/28993107/momentjs-how-to-prevent-invalid-date