简体   繁体   English

JavaScript验证日期的存在

[英]JavaScript validate existence of date

I have a date in the format YYMMDD. 我有一个日期格式为YYMMDD的日期。 Is there anyway I can validate it in JavaScript? 无论如何,我可以用JavaScript进行验证吗? By validation I don't mean easier things like length, characters etc but rather if the date exists in real life. 通过验证,我并不是说简单的东西,例如长度,字符等,而是如果日期存在于现实生活中。

I'm hoping there is a faster / better way than breaking it in 3 chunks of 2 characters and checking each individually. 我希望有一种比将其分成2个字符的3个块并将每个块单独检查更快/更好的方法。

Thank you. 谢谢。

try to convert it to a date and if it fails, you get the dreaded NaN then you know it is not a valid date string? 尝试将其转换为日期,如果失败,则得到可怕的NaN然后知道它不是有效的日期字符串? Not Pretty but it should work 不漂亮,但应该可以

var myDate = new Date(dateString);
// should write out NaN
document.write("Date : " + myDate);

You date string would have to be in a valid format for javascript I don't think what you have in your question YYMMDD is supported 您的日期字符串必须采用有效的javascript格式,我认为您的问题YYMMDD不支持

The format YYMMDD is not supported by Javascript Date.parse so you have to do some processing of it like breaking it in parts. Javascript Date.parse不支持YYMMDD格式,因此您必须对其进行一些处理,例如将其分成几部分。

I would suggest building a function that splits it in 3 2 char strings and then builds an american style date 我建议构建一个将其分成3 2个char字符串的函数,然后构建一个美式日期

MM/DD/YY and try to parse that with Date.parse. MM / DD / YY,然后尝试使用Date.parse进行解析。

If it returns anything but NaN then its a valid date. 如果返回除NaN以外的任何值,则其为有效日期。

The Date parser in JavaScript is pretty useless. JavaScript中的Date解析器几乎没有用。 The actual formats it accepts vary greatly across browsers; 它在各种浏览器中接受的实际格式差异很大。 the only formats guaranteed to work by the ECMAScript standard are whatever formats the implementation's toString and toUTCString methods produce. ECMAScript标准保证的唯一可用格式是实现的toStringtoUTCString方法产生的任何格式。 In ECMAScript Fifth Edition you will also get ISO-8166 format, which is nearer to your format but still not quite. 在ECMAScript第五版中,您还将获得ISO-8166格式,该格式与您的格式更接近,但仍不完全相同。

So, the best solution is usually to parse it yourself. 因此,最好的解决方案通常是自己解析。

var y= parseInt(s.slice(0, 2), 10)+2000;
var m= parseInt(s.slice(2, 4), 10)-1;
var d= parseInt(s.slice(4, 6), 10);
var date= new Date(Date.UTC(y, m, d));

Now you've got a Date object representing the input date in UTC. 现在,您已获得一个Date对象,该对象代表UTC中的输入日期。 But that's not enough, because the Date constructor allows bogus months like 13 or days like 40, wrapping around. 但这还不够,因为Date构造函数允许假的月份(如13)或天(如40)环绕。 So to check the given day was a real day, convert back to year/month/day and compare: 因此,要检查给定的一天是真实的一天,请转换回年/月/日并进行比较:

var valid= date.getUTCFullYear()===y && d.getUTCMonth()===m && d.getUTCDate()===d;

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

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