简体   繁体   中英

How to validate a Datetime value in javascript?

如何在javascript中验证日期时间值,以确保输入的年,月,日,小时,分钟和秒的值组成有效的Datetime对象?

Perhaps something like that:

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;
}

Tested with:

"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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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