JavaScript如何验证日期?

我正在尝试测试以确保某个日期有效(如果有人输入2/30/2011则应该是错误的)。

我如何在任何日期都可以这样做?

回答:

验证日期字符串的一种简单方法是将其转换为日期对象并进行测试,例如

// Expect input as d/m/y

function isValidDate(s) {

var bits = s.split('/');

var d = new Date(bits[2], bits[1] - 1, bits[0]);

return d && (d.getMonth() + 1) == bits[1];

}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {

console.log(s + ' : ' + isValidDate(s))

})

以这种方式测试日期时,仅需要测试月份,因为如果日期超出范围,则月份会更改。如果月份超出范围,则相同。任何年份均有效。

您还可以测试日期字符串的位:

function isValidDate2(s) {

var bits = s.split('/');

var y = bits[2],

m = bits[1],

d = bits[0];

// Assume not leap year by default (note zero index for Jan)

var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

// If evenly divisible by 4 and not evenly divisible by 100,

// or is evenly divisible by 400, then a leap year

if ((!(y % 4) && y % 100) || !(y % 400)) {

daysInMonth[1] = 29;

}

return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]

}

['0/10/2017','29/2/2016','01/02'].forEach(function(s) {

console.log(s + ' : ' + isValidDate2(s))

})

以上是 JavaScript如何验证日期? 的全部内容, 来源链接: utcz.com/qa/406693.html

回到顶部