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
223 views
in Technique[技术] by (71.8m points)

javascript - Convert utc time to timezone time using an offset in minutes C#

  1. The frontend sends a timezoneOffsetInMinutes

var timezoneOffsetInMinutes = new Date().getTimezoneOffset();
console.log(timezoneOffsetInMinutes);
question from:https://stackoverflow.com/questions/66055188/convert-utc-time-to-timezone-time-using-an-offset-in-minutes-c-sharp

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

1 Reply

0 votes
by (71.8m points)

To answer your question directly as asked:

public DateTimeOffset GetDateTimeOffsetAtTimezone(int timezoneOffsetInMinutes)
{
    // Start out with the current UTC time as a DateTimeOffset
    DateTimeOffset utc = DateTimeOffset.UtcNow;

    // Get the offset as a TimeSpan
    TimeSpan offset = TimeSpan.FromMinutes(timezoneOffsetInMinutes);

    // Apply the offset to the UTC time to calculate the resulting DateTimeOffset
    DateTimeOffset result = utc.ToOffset(offset);

    return result;
}

That said - be sure you are only doing this when you are relaying the current time zone offset - the one that's valid now on the client, and now on the server (a reasonable transmission delay is acceptable). To understand why, refer to to "Time Zone != Offset" in the timezone tag wiki.

If you also need to work with times other than now, then you'll need to instead gather the time zone ID from the client, not the offset.

var timeZoneId = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZoneId);

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

...