我有一个页面,当前正在使用日期时间微格式来显示时间戳,但我只显示了我自己时区的人类可读时间:
Friday, January 9, 2009 at 9:16 am (EST)
我想要做的是将abbr标签的innerHTML重写为相同的格式,但是在用户的本地时区.因此,对于西雅图的读者,上述内容应转换为:
Friday, January 9, 2009 at 6:16 am (PST)
我查看了Javascript Date对象,它允许我获取本地时区偏移量.但我有一些问题:
我没有看到从ISO-8601时间戳创建新Date对象的简单方法.(我想如果没有更快的方法,我可以解析子串或正则表达式.)
我没有看到获得时区命名缩写的方法.例如,对于西雅图的读者,我希望有时间将"(PST)"附加到最后,否则该用户不清楚时间戳已被转换(特别是如果他是常客和已经习惯了我的时代在EST).
Tony.. 5
这是我的代码解析ISO时间戳:
function isoDateStringToDate (datestr) { if (! this.re) { // The date in YYYY-MM-DD or YYYYMMDD format var datere = "(\\d{4})-?(\\d{2})-?(\\d{2})"; // The time in HH:MM:SS[.uuuu] or HHMMSS[.uuuu] format var timere = "(\\d{2}):?(\\d{2}):?(\\d{2}(?:\\.\\d+)?)"; // The timezone as Z or in +HH[:MM] or -HH[:MM] format var tzre = "(Z|(?:\\+|-)\\d{2}(?:\\:\\d{2})?)?"; this.re = new RegExp("^" + datere + "[ T]" + timere + tzre + "$"); } var matches = this.re.exec(datestr); if (! matches) return null; var year = matches[1]; var month = matches[2] - 1; var day = matches[3]; var hour = matches[4]; var minute = matches[5]; var second = Math.floor(matches[6]); var ms = matches[6] - second; var tz = matches[7]; var ms = 0; var offset = 0; if (tz && tz != "Z") { var tzmatches = tz.match(/^(\+|-)(\d{2})(\:(\d{2}))$/); if (tzmatches) { offset = Number(tzmatches[2]) * 60 + Number(tzmatches[4]); if (tzmatches[1] == "-") offset = -offset; } } offset *= 60 * 1000; var dateval = Date.UTC(year, month, day, hour, minute, second, ms) - offset; return new Date(dateval); }
不幸的是,它也没有处理时区缩写.你必须修改"tzre"表达式来接受字母,我知道在Javascript中处理时区缩写的唯一解决方案是有一个查找表,你可以在更改区域时手动保持最新状态夏令时.
这是我的代码解析ISO时间戳:
function isoDateStringToDate (datestr) { if (! this.re) { // The date in YYYY-MM-DD or YYYYMMDD format var datere = "(\\d{4})-?(\\d{2})-?(\\d{2})"; // The time in HH:MM:SS[.uuuu] or HHMMSS[.uuuu] format var timere = "(\\d{2}):?(\\d{2}):?(\\d{2}(?:\\.\\d+)?)"; // The timezone as Z or in +HH[:MM] or -HH[:MM] format var tzre = "(Z|(?:\\+|-)\\d{2}(?:\\:\\d{2})?)?"; this.re = new RegExp("^" + datere + "[ T]" + timere + tzre + "$"); } var matches = this.re.exec(datestr); if (! matches) return null; var year = matches[1]; var month = matches[2] - 1; var day = matches[3]; var hour = matches[4]; var minute = matches[5]; var second = Math.floor(matches[6]); var ms = matches[6] - second; var tz = matches[7]; var ms = 0; var offset = 0; if (tz && tz != "Z") { var tzmatches = tz.match(/^(\+|-)(\d{2})(\:(\d{2}))$/); if (tzmatches) { offset = Number(tzmatches[2]) * 60 + Number(tzmatches[4]); if (tzmatches[1] == "-") offset = -offset; } } offset *= 60 * 1000; var dateval = Date.UTC(year, month, day, hour, minute, second, ms) - offset; return new Date(dateval); }
不幸的是,它也没有处理时区缩写.你必须修改"tzre"表达式来接受字母,我知道在Javascript中处理时区缩写的唯一解决方案是有一个查找表,你可以在更改区域时手动保持最新状态夏令时.