在IE中解析日期 [英] Parse date in IE
问题描述
我具有以下日期格式:
Tue Mar 06 17:45:35 -0600 2012
,我想使用Javascript中的new Date()
对其进行解析.
and I want to parse it using new Date()
in Javascript.
幸运的是,这在Chrome中有效,但在IE中不起作用(返回无效日期).
Fortunately this works in Chrome but does not work in IE (returns invalid date).
有什么建议吗?
尝试使用:
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if (parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if (month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
推荐答案
在ECMA-262第3版中,Date.parse完全依赖于实现.在ES5中,仅应正确解析ISO8601字符串,其他任何事情都取决于实现.
In ECMA-262 ed 3, Date.parse was entirely implementation dependent. In ES5, only ISO8601 strings should be correctly parsed, anything else is up to the implementation.
以下是OP格式的手动解析:
Here's a manual parse of the OP format:
var s = 'Tue Mar 06 17:45:35 -0600 2012'
function parseIt(s) {
var months = {Jan:0, Feb:1, Mar:2, Apr:3, May:4, Jun:5,
Jul:6, Aug:7, Sep:8, Oct:9, Nov:10, Dec:11};
// Split the string up
var s = s.split(/[\s:]/);
// Create a date object, setting the date
var d = new Date(s[7], months[s[1]], s[2]);
// Set the time
d.setHours(s[3], s[4], s[5], 0);
// Correct the timezone
d.setMinutes(d.getMinutes() + Number(s[6]) - d.getTimezoneOffset());
// Done
return d;
}
alert(s + '\n' + parseIt(s));
编辑
时区行中的标志本来是错误的,现在它们是正确的.哦,我假设"-0600"是一个相当于GMT + 1000(例如AEST)的javascript时区偏移量.
Edit
The signs in the timezone line were originally wrong, they're correct now. Oh, and I'm assuming the '-0600' is a javascript timezone offset equivalent to GMT+1000 (e.g. AEST).
这篇关于在IE中解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!