javascript JS 检查有效的日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14693298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:19:49  来源:igfitidea点击:

JS check for valid date format

javascriptvalidationdatetime

提问by

I have a text field where a user inputs a date-time in the format: dd/mm/YYYY hh:ii. I want to check if this is a valid date-time using javascript. This should include 29th of february and everything. How can I do that? A regex won't succeed due to special months.

我有一个文本字段,用户可以在其中输入以下格式的日期时间:dd/mm/YYYY hh:ii. 我想使用 javascript 检查这是否是有效的日期时间。这应该包括 2 月 29 日和一切。我怎样才能做到这一点?由于特殊月份,正则表达式不会成功。

采纳答案by Rachel Gallen

see http://internotredici.com/article/checkdateinjavascript/for a helpful article on checking the time - just what you want!

有关检查时间的有用文章,请参阅http://internotredici.com/article/checkdateinjavascript/- 正是您想要的!

below is full text of article

以下是文章全文

Check date in javascript Article published on January 31, 2006 under Scripting Programmers very often needs to validate informations inserted into forms and to check their correctness is useful take advantage from javascript. This tutorial will explain how to use javascript in order to verify if a date is valid or not. Dates in forms are inserted in two different ways, the first uses a text field where user type data following different patterns (in this tutorial we assume that dates are in dd-mm-yyyy format); the second uses instead pulldown menus. The first solution is more simple to carry out, but is subject to more errors by users (for example inserting invalid characters or more frequent typing dates in a format different from the one that have been planned). Suppose now that we have the following text field in which we want to insert a date in dd-mm-yyyy format:

检查 javascript 中的日期 2006 年 1 月 31 日发布在脚本程序员下的文章经常需要验证插入表单的信息并检查它们的正确性,这对利用 javascript 很有用。本教程将解释如何使用 javascript 来验证日期是否有效。表单中的日期以两种不同的方式插入,第一种使用文本字段,用户可以在其中按照不同的模式键入数据(在本教程中,我们假设日期采用 dd-mm-yyyy 格式);第二个使用下拉菜单。第一种解决方案实施起来更简单,但会受到用户更多错误的影响(例如,插入无效字符或以与计划格式不同的格式更频繁地键入日期)。

<form id="test_form" action="get" method="/checkdatejavascript" 
onsubmit="return(check_form(this)); return false;">
<input type="text" name="datefield" id="datefield" />
</form>

To check the correctness of inserted data we will use the check_form function:

为了检查插入数据的正确性,我们将使用 check_form 函数:

function check_form()
{
// Regular expression used to check if date is in correct format
var pattern = new RegExp([0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2});
if(document.getElementById('datefield').value.match(pattern))
{
  var date_array = document.getElementById('datefield')
                   .value.split('-');
  var day = date_array[0];

  // Attention! Javascript consider months in the range 0 - 11
  var month = date_array[1] - 1;
  var year = date_array[2];

  // This instruction will create a date object
  source_date = new Date(year,month,day);

  if(year != source_date.getFullYear())
  {
     alert('Year is not valid!');
     return false;
  }

  if(month != source_date.getMonth())
  {
     alert('Month is not valid!');
     return false;
  }

  if(day != source_date.getDate())
  {
     alert('Day is not valid!');
     return false;
  }
}
else
{
  alert('Date format is not valid!');
  return false;
}

return true;

} As we can see, the regular expression evidenced in blue is use to control if inserted date follows or not the default assigned format. If the pattern is valid then function proceed to the next step otherwise an error message is raised abd form is not sent (the regular expression guarantees moreover that date cannot be empty). To validate the date we will use the Date object offered by javascript. (check the code evidenced in red). The algorithm is pretty simple. Using the informations inserted by user we will create a Date object and using the methods getFullYear, getMonth and getDate we will produce three values representing respectively the year, the month and the day associated to it. If these values are equal to those inserted by user, then the date is correct. Consider now the following examples:

如我们所见,蓝色的正则表达式用于控制插入的日期是否遵循默认指定的格式。如果模式有效,则函数继续下一步,否则会引发错误消息,并且不会发送表单(正则表达式还保证该日期不能为空)。为了验证日期,我们将使用 javascript 提供的 Date 对象。(检查红色证明的代码)。算法非常简单。使用用户插入的信息,我们将创建一个 Date 对象,并使用 getFullYear、getMonth 和 getDate 方法生成三个值,分别代表与其关联的年、月和日。如果这些值与用户插入的值相同,则日期是正确的。现在考虑以下示例:

User insert in text field the string 09-01-1976 Date object created from string is 09-01-1976 Date is valid

用户在文本字段中插入字符串 09-01-1976 从字符串创建的日期对象是 09-01-1976 日期有效

User insert in text field the string 31-02-2006 Date object created from string is 03-03-2006 Date is not valid

用户在文本字段中插入字符串 31-02-2006 从字符串创建的日期对象是 03-03-2006 日期无效

Programmer had to take particular attention (check the code evidenced in green) in the way javascript handles dates, because months are considered in the range from 0 to 11 assuming that o is January and 11 is December. In case of pulldown menus are used to insert dates, controls are more simple due to the fact that regular expression is not need to validate date format:

程序员必须特别注意 javascript 处理日期的方式(检查绿色代码),因为假设 o 是 1 月,11 是 12 月,月份被认为是在 0 到 11 的范围内。在使用下拉菜单插入日期的情况下,由于不需要正则表达式验证日期格式,因此控件更加简单:

  <form id="test_form" action="get" method="/checkdatejavascript" 
   onsubmit="return(check_form(this)); return false;">
  <select name="dateday" id="dateday">
  <option value="1">1</option>
     […]
  </select>
  <select name="datemonth" id="datemonth">
  <option value="0">January</option>
     […]
   </select>
   <select name="dateyear" id="dateyear">
  <option value="2006">2006</option>
     […]
  </select>
  </form>

The javascript function that will controll date correctness is

将控制日期正确性的 javascript 函数是

 function check_form()
{
 var day = document.getElementById('dateday').value;
 var month = document.getElementById('datemonth').value;
 var year = document.getElementById('dateyear').value;

 // This instruction will create a date object
 source_date = new Date(year,month,day);

 if(year != source_date.getFullYear())
{
   alert('Year is not valid!');
   return false;
}

if(month != source_date.getMonth())
{
  alert('Month is not valid!');
  return false;
}

if(day != source_date.getDate())
{
  alert('Day is not valid!');
  return false;
}

 return true;
}

Update: I have updated the code, because there was an issue with the regular expression. Thanks to Alex for the advice

更新:我已经更新了代码,因为正则表达式存在问题。感谢亚历克斯的建议

回答by JYing

If using moment.js is ok, you can check http://momentjs.com/docs/#/parsing/string-format/for date-time parsing utilities. For example:

如果使用 moment.js 没问题,您可以检查http://momentjs.com/docs/#/parsing/string-format/以获取日期时间解析实用程序。例如:

moment("29/02/2014 11:45", "DD/MM/YYYY hh:mm", true).isValid()

回答by Sony Mathew

If you dont want to use other external libraries you can use the following function :

如果不想使用其他外部库,可以使用以下函数:

var validateDate = function(dateTime){
  var f_date = dateTime.split(" ")[0].split("/").reverse().join("/");
  var time = dateTime.split(" ")[1];

  var date = dateTime.split(" ")[0].split("/").map(function(c, i, a){
        return parseInt(c);
    });
  var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
  if ( (!(date[2] % 4) && date[2] % 100) || !(date[2] % 400)) {
    console.log("inside");
    daysInMonth[1] = 29;
  }

  if(date[0] > 0 && (date[0] <= daysInMonth[(date[1]-1)]) && date[1] > 0 && date[1] <= 12){
    return new Date(f_date + " " + time) != "Invalid Date";
  }
  return false;
}

This will take care of leap year variations also. This function will work only if the input is in the format dd/mm/YYYY hh:ii. You can try some sample inputs like this:

这也将处理闰年变化。仅当输入为 格式时,此功能才有效dd/mm/YYYY hh:ii。您可以尝试一些示例输入,如下所示:

validateDate("29/2/2000 12:30"); // Should return true
validateDate("29/2/2001 12:30"); // Should return false
validateDate("32/8/2000 12:30"); // Should return false
validateDate("30/11/2000 12:30"); // Should return true
validateDate("31/4/2000 12:30"); // Should return false
validateDate("15/7/2000 12:77"); // Should return false