使用 JavaScript 获取特定时区的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11124322/
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-08-24 04:35:26  来源:igfitidea点击:

Get date time for a specific time zone using JavaScript

javascriptdate

提问by Yang

It seems that JavaScript's Date() function can only return local date and time. Is there anyway to get time for a specific time zone, e.g., GMT-9?

JavaScript 的 Date() 函数似乎只能返回本地日期和时间。有没有办法获得特定时区的时间,例如 GMT-9?

Combining @?Esailija and @D3mon-1stVFW, I figured it out: you need to have two time zone offset, one for local time and one for destination time, here is the working code:

结合@?Esalija 和@D3mon-1stVFW,我想通了:你需要有两个时区偏移,一个用于本地时间,一个用于目的地时间,这是工作代码:

var today = new Date();  
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4; 

var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000)

An example is here: http://jsfiddle.net/BBzyN/3/

一个例子在这里:http: //jsfiddle.net/BBzyN/3/

采纳答案by Esailija

var offset = -8;
new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )

"Wed, 20 Jun 2012 08:55:20"

<script>
  var offset = -8;

  document.write(
    new Date(
      new Date().getTime() + offset * 3600 * 1000
    ).toUTCString().replace( / GMT$/, "" )
  );
</script>

回答by Hitham S. AlQadheeb

var today = new Date();  
var offset = -(today.getTimezoneOffset()/60);  

回答by E. Karim

You can do this in one line:

您可以在一行中执行此操作:

let d = new Date(new Date().toLocaleString("en-US", {timeZone: "timezone id"})); // timezne ex: Asia/Jerusalem

回答by hdogan

There is simple library for working on timezones easily called TimezoneJS can be found at https://github.com/mde/timezone-js.

可以在https://github.com/mde/timezone-js上找到一个简单的用于处理时区的库,很容易称为 TimezoneJS 。

回答by kennebec

You can always get GMT time (so long as the client's clock is correct).

您始终可以获得 GMT 时间(只要客户的时钟是正确的)。

To displaya date in an arbitrary time-zone, construct a string from the UTC hours, minutes, and seconds after adding the offset.

要在任意时区显示日期,请在添加偏移量后根据 UTC 小时、分钟和秒构造一个字符串。