我有以下日期格式:
Tue Mar 06 17:45:35 -0600 2012
我希望在Javascript中使用new Date()
解析它。
幸运的是,这适用于Chrome,但在IE中无效(返回无效日期)。
有什么建议吗?
试图使用:
/**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;
}
答案 0 :(得分:2)
在ECMA-262 ed 3中,Date.parse完全依赖于实现。在ES5中,只应正确解析ISO8601字符串,其他任何内容都取决于实现。
以下是OP格式的手动解析:
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时区偏移量。