栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript如何验证日期?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript如何验证日期?

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

// Expect input as d/m/yfunction 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))})


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415931.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号