且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript检测有效日期

更新时间:2023-11-27 23:13:16

有效的可以解析日期的组件,从中创建一个 Date 对象,并检查数据中的组件是否与解析的组件相同。如果您从超出范围的组件创建了 Date 对象,则值将流过下一个/上一个时间段以创建有效的日期。

To check if a date is valid you can parse the components of the date, create a Date object from it, and check if the components in the data is the same as the parsed components. If you create a Date object from compnents that are out of range, the values will flow over to the next/previous period to create a valid date.

例如, new Date(2011,0,42)将创建一个包含日期2/11/2011而不是1的对象/ 42/2011。

For example, new Date(2011,0,42) will create an object that contains the date 2/11/2011 instead of 1/42/2011.

通过解析组件而不是完整的日期,您还可以解决不同日期格式的问题。例如,我的浏览器会希望使用日期格式,例如 ymd 而不是 d / m / y

By parsing the components instead of the full date you will also get around the problem with different date formats. My browser will for example expect a date format like y-m-d rather than d/m/y.

示例:

var text = '2/30/2011';
var comp = text.split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y,m-1,d);
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
  alert('Valid date');
} else {
  alert('Invalid date');
}

演示: http://jsfiddle.net/Guffa/UeQAK/