JavaScript 转换为 PC 时区

JavaScript converts to PC timezone

Javascript是否可以转换指定时区的日期,比如Europe/Berlin传给浏览器的时区?

有些图书馆可以做到这一点。虽然从工程的角度来看这不是一个特别困难的问题,但有数量惊人的边缘情况难以解决。

建议的图书馆:moment.js

手动执行此操作的步骤:

  1. 计算目标日期的 UTZ 时区偏移量
  2. 计算浏览器的 UTZ 时区偏移量
  3. 找到目标和浏览器之间的总时区偏移量。
  4. 调整夏令时问题(是的,这是困难的部分)

使用 moment.js, with the moment-timezone 插件:

// parse in a particular time zone
var m = moment.tz("2014-12-31T01:23:45", "Europe/Berlin"); 

// switch to the browser's local time zone
m.local(); 

// format some output
m.format(); // example: "2014-12-30T16:23:45-08:00"

如果您愿意,可以一行完成。

moment.tz("2014-12-31T01:23:45", "Europe/Berlin").local().format()