javascript 从特定时区获取当前时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9576786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:06:19  来源:igfitidea点击:

Get current timestamp from specific timezone

javascripttimezoneunix-timestamptimezone-offset

提问by Toby

is there an easy way to get the unix timestamp in javascript from a specific timezone? for example i want the client send me an unix timestamp but i want to get it to match my timezone.

有没有一种简单的方法可以从特定时区获取 javascript 中的 unix 时间戳?例如,我希望客户端向我发送一个 unix 时间戳,但我想让它与我的时区相匹配。

thanks!

谢谢!

采纳答案by tjdett

Why not simply send the date in UTC, and then convert to your timezone on the server?

为什么不简单地以 UTC 格式发送日期,然后在服务器上转换为您的时区?

var utcEpochSeconds = dateObj.getTime() + (dateObj.getTimezoneOffset() * 60000);

回答by Trevor

Use toISOStringto get a UTC timestamp.

使用toISOString获得UTC时间戳。

var date = new Date();
date.toISOString(); // EST would be 6 hour diff from GMT

回答by Eli

In order for this to happen, you need to apply the timezone offset to the time, and then remove your offset from value (test this, I am guessing from memory):

为了实现这一点,您需要将时区偏移量应用于时间,然后从值中删除您的偏移量(测试这个,我是从记忆中猜测的):

var now = new Date(),
    offset = -(now.getTimezoneOffset() * 60 * 1000), // now in milliseconds
    userUnixStamp = +now + offset;

Now offset from your own:

现在从你自己的抵消:

var now = new Date(),
    offset = now.getTimezoneOffset() * 60 * 1000,
    yourUnixStamp = userUnixStamp - offset;