如何在 javascript 中获取 UTC 偏移量(类似于 C# 中的 TimeZoneInfo.GetUtcOffset)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9149556/
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
How to get UTC offset in javascript (analog of TimeZoneInfo.GetUtcOffset in C#)
提问by Andrei M
In C# you can use
在 C# 中,您可以使用
System.TimeZone.CurrentTimeZone.GetUtcOffset(someDate).Hours
But how can I get UTC offset in hours for a certain date (Date object) in javascript?
但是如何在javascript中以小时为单位获得某个日期(日期对象)的UTC偏移量?
回答by Allan
Vadim's answer might get you some decimal points after the division by 60; not all offsets are perfect multiples of 60 minutes. Here's what I'm using to format values for ISO 8601 strings:
Vadim 的答案可能会在除以 60 后得到一些小数点;并非所有偏移量都是 60 分钟的完美倍数。这是我用来格式化 ISO 8601 字符串值的内容:
function pad(value) {
return value < 10 ? '0' + value : value;
}
function createOffset(date) {
var sign = (date.getTimezoneOffset() > 0) ? "-" : "+";
var offset = Math.abs(date.getTimezoneOffset());
var hours = pad(Math.floor(offset / 60));
var minutes = pad(offset % 60);
return sign + hours + ":" + minutes;
}
This returns values like "+01:30" or "-05:00". You can extract the numeric values from my example if needed to do calculations.
这将返回诸如“+01:30”或“-05:00”之类的值。如果需要进行计算,您可以从我的示例中提取数值。
Note that getTimezoneOffset()
returns a the number of minutes difference from UTC, so that value appears to be opposite (negated) of what is needed for formats like ISO 8601. Hence why I used Math.abs()
(which also helps with not getting negative minutes) and how I constructed the ternary.
请注意,getTimezoneOffset()
返回与 UTC 的分钟数差异,因此该值似乎与 ISO 8601 等格式所需的值相反(否定)。因此我使用Math.abs()
(这也有助于不获得负分钟数)以及我如何构建三元。
回答by Chris W.
I highlyrecommend using the moment.js libraryfor time and date related Javascript code.
我强烈建议使用moment.js 库来处理与时间和日期相关的 Javascript 代码。
In which case you can get an ISO 8601formatted UTC offset by running:
在这种情况下,您可以通过运行获得ISO 8601格式的 UTC 偏移量:
> moment().format("Z")
> "-08:00"
回答by Vadim Gulyakin
<script type="text/javascript">
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
</script>