计算另一个时区的日期和时间 [英] Calculating a date and time in another time zone

查看:363
本文介绍了计算另一个时区的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经让我扭转了好几天了。

This has been driving me around the twist for several days now.

该应用程序是使用JavaScript。

The application is in JavaScript.

我希望在一个时区中为另一个时区的观众显示时间。

I'm wish to show the time in one time zone for a viewer in another time zone.

我会存储GMT的时区偏移(夏令时会我想要显示时间和日期的区域,以便考虑到偏移量。

I would store the time zone offset from GMT (Daylight saving would be taken in to account with the offset) for the zone I want to display the time and date for.

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

I was planning on converting the time to Epoch and then adding or subtracting the offset and then convert to DD MM YYYY HH MM SS for the date calculated.

我已经到了无法再看到木头的地步树木。关于如何实现这一点的任何想法。

I've got to the point that I can no longer see the wood for the trees. Any thoughts on how to achieve this.

推荐答案

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

Since Dates are based on a UTC time value, you can just adjust for the offset you want and read UTC values, e.g.

/* @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的值。

Note that the offset has the same sign as the javascript Date timezone offset, which is opposite to the typical value that is added to UTC to get the local time.

这篇关于计算另一个时区的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆