Francisc
Francisc

Reputation: 80435

JavaScript validate existence of date

I have a date in the format YYMMDD. Is there anyway I can validate it in 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.

Thank you.

Upvotes: 1

Views: 676

Answers (3)

bobince
bobince

Reputation: 536409

The Date parser in JavaScript is pretty useless. 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. In ECMAScript Fifth Edition you will also get ISO-8166 format, which is nearer to your format but still not quite.

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. But that's not enough, because the Date constructor allows bogus months like 13 or days like 40, wrapping around. 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;

Upvotes: 1

David Mårtensson
David Mårtensson

Reputation: 7600

The format YYMMDD is not supported by Javascript Date.parse so you have to do some processing of it like breaking it in parts.

I would suggest building a function that splits it in 3 2 char strings and then builds an american style date

MM/DD/YY and try to parse that with Date.parse.

If it returns anything but NaN then its a valid date.

Upvotes: 1

Aaron Saunders
Aaron Saunders

Reputation: 33345

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? 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

Upvotes: 3

Related Questions