The best way to do this without any plugins or libraries is to first grab all the datetime components via RegEx to test if the input string is formatted correctly in the first place:
var test_str = '091603Z Apr 14';
var date_matches = test_str.match(/^(\d{2})(\d{2})(\d{2})Z (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2})$/);
// date_matches = ["091603Z Apr 14", "09", "16", "03", "Apr", "14"];
Then parse a correctly formatted/compiled string that Date.parse
can properly parse:
var s = Date.parse(date_matches[4] + ' ' + date_matches[1] + ', ' + date_matches[5] + ' ' + date_matches[2] + ':' + date_matches[3]);
// s = 1397073780000;
And just to ensure we've used a properly formatted string for parsing the date:
var date = new Date(1397073780000);
// date = Wed Apr 09 2014 16:03:00 GMT-0400 (EDT)
If the original string was invalid then Date.parse
would return NaN
, so you can simply test with isNaN()
.