Momentjs : How to prevent “Invalid date”?

前端 未结 1 983
南方客
南方客 2021-02-12 12:06

I have the following code :

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

Sometimes moment(myDate).format(\"L\") returns \"Inva

相关标签:
1条回答
  • 2021-02-12 13:03

    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.

    0 讨论(0)
提交回复
热议问题