How could I turn this string
Sun Apr 25, 2010 3:30pm
Into a valid Date in JavaScript (Minimal code is what I'm aiming for here)?
How could I turn this string
Sun Apr 25, 2010 3:30pm
Into a valid Date in JavaScript (Minimal code is what I'm aiming for here)?
You could try Datejs http://www.datejs.com/ This would not require much coding on your part, but would require including this script in your html.
Date.parse
almost gets you what you want. It chokes on the am
/pm
part, but with some hacking you can get it to work:
var str = 'Sun Apr 25, 2010 3:30pm',
timestamp;
timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
if(str.match(/pm$/i) >= 0) {
timestamp += 12 * 60 * 60 * 1000;
}
Minicode looks like this:
var s = 'Sun Apr 25, 2010 3:30pm';
Date.parse(s.slice(0,-2))+432E5*/pm$/.test(s);
The outcome of your approach is not guaranteed by any specification.
ECMAScript Edition 3 is the pertinent one, and does not specify any formats that that Date.parse can parse. Moreover, the specification states that when Date.parse
is supplied a value that could not be produced by either Date.prototype.toString
or Date.prototype.toLocaleString
, the result is implementation-dependent.
...the value produced by
Date.parse
is implementation-dependent when given any string value that could not be produced in that implementation by thetoString
ortoUTCString
method.
Do not expect consistent results from Date.parse
when passing in your own locale-specific date format.
ISO-8601 format can be used and the value can be parsed by your program. See also: http://stackoverflow.com/questions/2182246/javascript-dates-in-ie-nan-firefox-chrome-ok