计算另一个时区的日期和时间

Calculating a date and time in another time zone

本文关键字:时间 日期 另一个 时区 计算      更新时间:2023-09-26

这几天我一直很纠结。

应用程序是用JavaScript编写的

我希望显示一个时区的时间给另一个时区的观众。

我将存储从GMT开始的时区偏移量(夏令时将被考虑到偏移量),用于我想要显示时间和日期的区域。

我计划将时间转换为Epoch,然后添加或减去偏移量,然后转换为计算日期的DD MM YYYY HH MM SS。

我已经到了只见树木不见森林的地步。有什么想法吗?

由于日期是基于UTC时间值,你可以调整你想要的偏移量并读取UTC值,例如

/* @param {number} offset - minutes to subtract from UTC to get time in timezone
**
*/
function getTimeForOffset(offset) {
  function z(n){return (n<10?'0':'')+n}
  var now = new Date();
  now.setUTCMinutes(now.getUTCMinutes() - offset);
  return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}
// Time for AEST (UTC+10)
console.log(getTimeForOffset(-600));
// Time for CEST (UTC+02)
console.log(getTimeForOffset(-120));

请注意,该偏移量与javascript Date时区偏移量具有相同的符号,这与添加到UTC以获得本地时间的典型值相反。