DD HH:MM:SS T
This question already has an answer here:
I deleted my previous (less relevant) answer. This function should suit your purposes much better.
The key strategy is to get an absolute representation of your time without the time zone, and then adjust it backward or forward based on the specified timezone. What it spits out is a Date
object in your browser's local time zone, but it will represent exactly the same moment in time as the string does.
Also, the format you specified isn't quite to spec, so the regex I wrote accepts your version as well as ISO8601.
Date.createFromString = function (string) {
'use strict';
var pattern = /^(dddd)-(dd)-(dd)[ T](dd):(dd):(dd)([+-Z])(dd):(dd)$/;
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);
};
Use moment.js's date parsing:
var date = moment("2012-05-23 12:12:00-05:00");
See http://momentjs.com/docs/#/parsing/string/
链接地址: http://www.djcxy.com/p/18614.html上一篇: Date.getDay()返回不同的值
下一篇: DD HH:MM:SS T