简体   繁体   English

在Javascript中验证日期

[英]Validate date in Javascript

Note that this seems like a question that is asked many times, but somehow I can't get the most common solution to work. 请注意,这似乎是一个多次被问到的问题,但不知怎的,我无法获得最常用的解决方案。 Most answers revolve around a solution like this one: 大多数答案都围绕这样的解决方案:

function isValidDate(){
  var dateString = '2001/24/33';
  return !isNaN(Date.parse(dateString));
}

In Firefox this returns a false as the result of that Date.parse is a number; 在Firefox中,由于Date.parse是一个数字,因此返回false; 1041462000000. 10414.62亿。

How do I fix this..? 我该如何解决..?

A good way to do this is to create new date object based on the string and compare the result of that object with the input string. 执行此操作的一种好方法是基于字符串创建新的日期对象,并将该对象的结果与输入字符串进行比较。 If it is not the same, the date was invalid and JS did a fallback to a closer (valid) date. 如果它不相同,则日期无效,JS回退到更近(有效)的日期。 Something like this: 像这样的东西:

function isValidDate(str){
   var split = str.split('/');
   var date = new Date(split[0], split[1]-1, split[2]);

   return (date.getFullYear() == split[0] && date.getMonth()+1 == split[1] && date.getDate() == split[2]);
}

call with: 致电:

var isValid = isValidDate('2001/24/33');

Note: in this case the input string is assumed to be in a specific format. 注意:在这种情况下,假定输入字符串采用特定格式。 If your sure that it's always the same format there is not problem. 如果您确定它始终采用相同的格式,则没有问题。 If not, your need the work some more on this code. 如果没有,您需要在此代码上进行更多工作。

As a sidenote: Use moment.js if you need to do extensive date operations. 作为旁注:如果您需要进行大量的日期操作,请使用moment.js

I suggest to use http://www.datejs.com/ . 我建议使用http://www.datejs.com/

Very cool library. 非常酷的图书馆。

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

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