我需要解析一个字符串到目前为止的格式
2012-05-23 12:12:00-05:00
Date.parse("2012-05-23 12:12:00-05:00")
它与chorme工作正常,但在Firefox和IE中没有。任何建议都会有所帮助。
答案 0 :(得分:0)
使用moment.js的日期解析:
var date = moment("2012-05-23 12:12:00-05:00");
答案 1 :(得分:0)
我删除了之前(不太相关)的答案。此功能应该更适合您的目的。
关键策略是在没有时区的情况下绝对表示您的时间,然后根据指定的时区向后或向前调整。它吐出的是浏览器本地时区中的Date
对象,但它将代表与字符串完全相同的时刻。
此外,您指定的格式不符合规范,因此我编写的正则表达式接受您的版本以及ISO8601。
Date.createFromString = function (string) {
'use strict';
var pattern = /^(\d\d\d\d)-(\d\d)-(\d\d)[ T](\d\d):(\d\d):(\d\d)([+-Z])(\d\d):(\d\d)$/;
var matches = pattern.exec(string);
if (!matches) {
throw new Error("Invalid string: " + string);
}
var year = matches[1];
var month = matches[2] - 1; // month counts from zero
var day = matches[3];
var hour = matches[4];
var minute = matches[5];
var second = matches[6];
var zoneType = matches[7];
var zoneHour = matches[8] || 0;
var zoneMinute = matches[9] || 0;
// Date.UTC() returns milliseconds since the unix epoch.
var absoluteMs = Date.UTC(year, month, day, hour, minute, second);
var ms;
if (zoneType === 'Z') {
// UTC time requested. No adjustment necessary.
ms = absoluteMs;
} else if (zoneType === '+') {
// Adjust UTC time by timezone offset
ms = absoluteMs - (zoneHour * 60 * 60 * 1000) - (zoneMinute * 60 * 1000);
} else if (zoneType === '-') {
// Adjust UTC time by timezone offset
ms = absoluteMs + (zoneHour * 60 * 60 * 1000) + (zoneMinute * 60 * 1000);
}
return new Date(ms);
};