日期在ISO格式的Chrome中无效-测试日期:2012-11-31

Date is invalid in Chrome with ISO format - tested with: 2012-11-31

本文关键字:日期 测试 2012-11-31 无效 Chrome ISO 格式      更新时间:2023-09-26

谁来回答我的问题?

如何使用Javascript跨浏览器验证日期

我使用无效日期:2011-11-31,如下所示:

var d = new Date("2012-11-31")

在FF中:

d = NaN // Date is invalid

在Chrome中:

d.getFullYear();//2012
d.getDate();//1
d.getMonth();//11

在IE7-9、chrome、opera、safari、firefox中进行了测试。此处测试:http://jsfiddle.net/MRwAq/

你可以这样做:

(function(){
                             //This should be good enough initial filter, let the native Date decide if the number are valid
    var validStringRE = /^([0-9]{4})-([0-1][0-9])-([0-3][0-9])$/;
    function pad( num ) {
    return num < 10 ? "0"+num : num;
    }
    Date.prototype.getISOFormat = function(){
    return this.getFullYear() + "-" +
    pad( ( this.getMonth() + 1 ) ) + "-" +
    pad( this.getDate() );
    };
    function isValidISODate( date ) {
    var matches, a;
        if( !validStringRE.test( date.toString() ) ) {
        return false; //Get rid of anything but "NNNN-NN-NN"
        }
    matches = date.match( validStringRE );
    a = new Date( +matches[1], +matches[2] - 1, +matches[3], 0, 0, 0, 0 );
        if( isNaN( a ) ) {
        return false; //firefox, ie
        }
        if( a.toString().toLowerCase() === "invalid date" ) {
        return false; //chrome in some cases, opera, safari
        }
    return a.getISOFormat() === date; //browsers that "conveniently" calculate
    }
window.isValidISODate = isValidISODate;
})()

然后:

var isValid = isValidISODate("2012-11-31");
//false
var isValid = isValidISODate("2012-11-30");
//true

你不能可靠地做到这一点。参见本标准第15.9.4.2节:

函数首先尝试解析字符串的格式根据日期时间字符串格式中的规则(15.9.1.15(。如果字符串不符合该格式,则函数可以回退到任何特定于实现的试探法,或者实现特定的日期格式。

从本质上讲,如果你输入了一个无效的日期,语言可以随心所欲,即退还NaN,或者尝试根据自己的意愿"修复"它。

Esailija发布了一种务实的测试方法,似乎效果良好。