Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...