如何验证日期? [英] How to validate a date?

查看:117
本文介绍了如何验证日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试以确保日期有效,因为如果有人输入 2/30/2011 那么它应该是错误的。

I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.

如何在任何日期执行此操作?

How can I do this with any date?

推荐答案

一个简单的方法验证日期字符串是否转换为日期对象并测试,例如

One simple way to validate a date string is to convert to a date object and test that, e.g.

// 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))
})

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

When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.

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

You can also test the bits of the date string:

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

这篇关于如何验证日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆