Skip to content Skip to sidebar Skip to footer

How To Turn A String Into A Date In Javascript

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

Solution 1:

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);

Solution 2:

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.

Solution 3:

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 the toString or toUTCString 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: Date constructor returns NaN in IE, but works in Firefox and Chrome

Post a Comment for "How To Turn A String Into A Date In Javascript"