简体   繁体   English

需要帮助,以确认是否使用JavaScript是过去的日期

[英]need help validating if a date is in the past using javascript

Hi I am currently stuck on how to carve up my regex date to then test if the date entered is in the past . 嗨,我目前停留在如何确定正则表达式日期,然后测试输入的日期是否为过去的日期上。 if it is I would like to alert this. 如果是的话,我想提醒一下。

I know i some how need to splice my regex but im unsure how to do this any help would be much appreciated. 我知道我有些需要拼接我的正则表达式的方法,但不确定如何做任何帮助将不胜感激。 below is my script so far its a pretty long regex but it covers everything including leap years but like i said i know need to break it down by either substr or splice. 下面是我的脚本,到目前为止,它是一个相当长的正则表达式,但是它涵盖了包括leap年在内的所有内容,但是就像我说的,我知道需要通过substr或splice来分解它。

//start of datefield
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/;

if (!date.match(dateformat))
{
    alert("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016");
    return false;
}
//end date field

Simple 简单

date = "12/11/2009";
if(new Date(date) < new Date()){
     // a
} else {
     // b
}

Using a regular expression to work out if a date is valid or is before or after some other time is not the easiest way to do the job. 使用正则表达式算出日期是否有效或在其他时间之前或之后不是最简单的方法。 Much easier to turn the string into a date object and test that. 将字符串转换为日期对象并进行测试要容易得多。

So parse the string to create a date object and go from there. 因此,分析字符串以创建日期对象,然后从那里开始。 You shouldn't leave parsing of date strings to the date object as it is mostly implementation dependent (ECMA-262 specifies a version of ISO8601 but it is not supported by all browsers in use). 您不应该将日期字符串的解析留给date对象,因为它主要取决于实现(ECMA-262指定了一个ISO8601版本,但并非所有使用的浏览器都支持它)。 So if your format is d/m/y you can do: 因此,如果您的格式是d / m / y,则可以执行以下操作:

function isDateHistory(s) {
  s = s.split('/');
  return (new Date(s[2], --s[1], s[0])) < (new Date());
}

alert(isDateHistory('15/6/2013')); // true
alert(isDateHistory('15/7/2013')); // false

You can also validate the date using: 您还可以使用以下方法验证日期:

function validateDate(dateString) {
  var s = dateString.split('/');
  var d = new Date(s[2], --s[1], s[0]);
  return d && d.getFullYear() == s[2] && d.getDate() == s[0];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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