简体   繁体   English

如何在JavaScript中比较两个日期(MonthName YearNumber)

[英]How to compare two dates (MonthName YearNumber) in javascript

This functionality is working fine in Chrome... But not IE or FF. 此功能在Chrome浏览器中工作正常……但是IE或FF却不能。

I am trying to validate two fields that take the value of MonthName YearNumber (see screenshot). 我正在尝试验证两个采用MonthName YearNumber的值的字段(请参见屏幕截图)。

形成

I am using Date.parse() to get miliseconds, then compare if Start Date <= End Date . 我正在使用Date.parse()获取毫秒,然后比较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: Firebug中显示的内容:

表格2

Since the format your date is in isn't universally supported you can try a library like Date.js : 由于您的日期格式不受普遍支持,因此您可以尝试使用类似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 . 如果您查看规范 “第15.9.1.15节日期时间字符串格式”,Ecmascript似乎不支持完整的月份名称。

In Firefox: 在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. 11 1999November 1999不是解析格式。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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