简体   繁体   中英

How to compare two dates (MonthName YearNumber) in javascript

This functionality is working fine in Chrome... But not IE or FF.

I am trying to validate two fields that take the value of MonthName YearNumber (see screenshot).

形成

I am using Date.parse() to get miliseconds, then compare if Start Date <= End Date .

function IsStartEndDtError(StartDt, EndDt) {
    //convert dates to miliseconds to compare if one is greater than other
    var StartDtMili = Date.parse(StartDt);
    var EndDtMili = Date.parse(EndDt);

    if (StartDtMili <= EndDtMili) {
        return false;
    }
    else {
        return true;
    }
}

What appears in Firebug:

表格2

Since the format your date is in isn't universally supported you can try a library like Date.js :

Date.parse("November 2012")
// returns: Thu Nov 01 2012 00:00:00 GMT+0000 (GMT)

If you don't want another library you can manually replace the month names with numbers and create a new date string.

Ecmascript does not seem to support full month names, if you look at "Section 15.9.1.15 Date Time String Format" in the spec .

In Firefox:

new Date("November 2012")
// Invalid Date
new Date("2012-11")
// Thu Nov 01 2012 00:00:00 GMT+0000 (GMT)

The second date format should be standardized across browsers, the first isn't.

11 1999 , November 1999 are not parsable formats. You either need to use a date library that is more flexible with its input formats, or process your input and identify the parts in it:

function IsStartEndDtError(StartDt, EndDt) {

    var months = {
        January: 0,
        February: 1,
        ...
    };

    //convert dates to miliseconds to compare if one is greater than other

    var StartDtMili = (new Date(StartDt.split(" ")[1], month[StartDt.split(" ")[0]])).getTime();
    var EndDtMili = (new Date(EndDt.split(" ")[1], month[EndDt.split(" ")[0]])).getTime();


    if (StartDtMili <= EndDtMili) {
        return false;
    }
    else {
        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM