如何在javascript中验证日期时间值以确保为年,月,日,小时,分钟和秒输入的值构成有效的Datetime对象?
也许是这样的:
function ValidateDate(y, mo, d, h, mi, s) { var date = new Date(y, mo - 1, d, h, mi, s, 0); var ny = date.getFullYear(); var nmo = date.getMonth() + 1; var nd = date.getDate(); var nh = date.getHours(); var nmi = date.getMinutes(); var ns = date.getSeconds(); return ny == y && nmo == mo && nd == d && nh == h && nmi == mi && ns == s; }
经测试:
"OK" ValidateDate(2001, 2, 28, 10, 35, 42) ValidateDate(2001, 12, 29, 10, 35, 42) ValidateDate(2000, 2, 29, 10, 35, 42) ValidateDate(2004, 2, 29, 10, 35, 42) ValidateDate(1970, 1, 2, 3, 4, 5) ValidateDate(2008, 1, 15, 10, 25, 44) "KO" ValidateDate(2001, 2, 29, 10, 35, 42) ValidateDate(2001, 11, 32, 10, 35, 42) ValidateDate(2001, 15, 2, 10, 35, 42) ValidateDate(2001, 1, 2, 25, 35, 42) ValidateDate(2001, 5, 2, 1, 61, 42) ValidateDate(2001, 5, 2, 1, 1, 70) ValidateDate(2001, 0, 2, 1, 1, 1) ValidateDate(2001, 2, 0, 1, 1, 1)