如何制作根据时区而变化的 DateTime 字符串?

How to make a DateTime string that changes depending on time zone?

我正在写一个网站,我想到了这个绝妙的主意。我会根据查看时区更改我的联系页面。

示例:

在当地时区 (GMT +1) 查看时:

I can be reached between 08:30 and 17:30

在纽约 (GMT -5) 查看时:

I can be reached between 03:30 and 12:30

在旧金山 (GMT -8):

I can be reached between 00:30 and 09:30

北京(GMT +8):

I can be reached between 16:30 and 01:30

...你懂的。

我不确定应该从哪里开始。我知道 moment.js 但我不确定它是否适合这个目的,'特别是考虑到我希望它由用户的当前位置自动确定这一事实。

我在服务器端使用 Node.js 和 Express.js,在客户端使用 jQuery。有帮助吗?

您可以使用 UTC 时间创建 Date 对象并从中获取本地时间。

// args are in UTC time
function toLocalTime(hours, minutes){
    var d = new Date(Date.UTC(0, 0, 1, hours, minutes, 0));
    return [d.getHours(), d.getMinutes()].map(function(x){
        return ('0' + x).slice(-2);
    }).join(':');
}

"I can be reached between " + toLocalTime(07, 30) + " and " + toLocalTime(16, 30)