开发者

How to turn a string into a date in Javascript

开发者 https://www.devze.com 2022-12-29 08:23 出处:网络
How could I turn this string Sun Apr 25, 2010 3:30pm Into a valid Date in JavaScript (开发者_如何学CMinimal code is what I\'m aiming for here)?Date.parse almost gets you what you want.It chokes on

How could I turn this string

Sun Apr 25, 2010 3:30pm

Into a valid Date in JavaScript (开发者_如何学CMinimal code is what I'm aiming for here)?


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消