本文介绍了如何获得UTC在javascript中的偏移量(在C#TimeZoneInfo.GetUtcOffset模拟)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,你可以使用

System.TimeZone.CurrentTimeZone.GetUtcOffset(someDate).Hours

但我怎样才能在UTC时间偏移在JavaScript中某一特定日期(Date对象)?

But how can I get UTC offset in hours for a certain date (Date object) in javascript?

推荐答案

瓦迪姆的答案可能让你被60师经过一番小数点;不是所有的偏移量是60分钟完美的倍数。下面是我用什么格式值ISO 8601的字符串:

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:

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;
}

这将返回象值+01:30或-05:00 。如果需要做计算,你可以从我的例子中提取的数值。

This returns values like "+01:30" or "-05:00". You can extract the numeric values from my example if needed to do calculations.

注意使用getTimezoneOffset()返回从UTC分钟的差异数,使价值似乎是相反的(否定)的什么是需要的格式,如ISO 8601。因此,为什么我用 Math.abs() (这也与没有得到负分帮助),我如何构造三元。

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.

这篇关于如何获得UTC在javascript中的偏移量(在C#TimeZoneInfo.GetUtcOffset模拟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 03:58