Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

How to get UTC offset in javascript (analog of TimeZoneInfo.GetUtcOffset in C#)

In C# you can use

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...