JavaScript的Date.parse适用于太平洋时间:
Date.parse('June 20 2015 10:22 PDT')
但它与阿拉斯加时间失败
Date.parse('June 20 2015 10:22 AKDT')
任何人都知道允许阿拉斯加时间的好方法吗?
1 个答案:
答案 0 :(得分:1)
JavaScript's Date.parse() method accepts date strings formatted according to RFC 2822 or ISO 8601.
RFC 2822, section 3.3, lists the parts of a valid date/time string. The zone rule says the time zone designator should either be a UTC-style offset (e.g. -0800), or an obs-zone (obsolete) time zone designator. Section 4.3 lists the obs-zone designators, which include the familiar PDT, CST, etc., but not AKDT.
ISO 8601 time zone designators are limited to UTC only.
In short, you should either use UTC offsets in place of designators like AKDT, or write a mapping function to convert those obsolete designators to UTC before passing the datetime string to Date.parse().
EDIT:
This code's algorithm is inherently buggy. As @MattJohnson notes in a comment to the original post, the obsolete time zone designators have several ambiguities - e.g. CST can map to 5 different UTC offsets. Therefore, there's no general solution that can replace a time zone designator with a UTC offset and be confident that the correct replacement was made.
var timeZoneDesignatorMap = {
akdt : '-0800',
akst : '-0900',
art : '-0300'
// Add other designators here.
};
function mappedDateParse(dateString) {
var name, newDateString, regex;
for (name in timeZoneDesignatorMap) {
regex = new RegExp(name, 'i');
if (dateString.search(regex) !== -1) {
newDateString = dateString.replace(regex, timeZoneDesignatorMap[name]);
return Date.parse(newDateString);
}
}
return Date.parse(dateString);
}
console.log(mappedDateParse('June 20 2015 10:22 AKDT'));
console.log(mappedDateParse('June 20 2015 10:22 -0800'));
console.log(mappedDateParse('June 20 2015 10:22 pDT'));