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

Categories

From JavaScript I have passed, to the controller, the number of minutes that the user's client date time is offset from UTC using the method getTimezoneOffset on the Date object. Now that I have this information on the server side I'd like to create a TimeZoneInfo from it. How is this possible? If this is not possible then how can I convert UTC dates on the server side into the client's timezone using the minutes offset?

See Question&Answers more detail:os

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

1 Answer

I'd like to create a TimeZoneInfo from it. How is this possible?

It's not possible. A time zone offset is not the same thing as a time zone. Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".

... then how can I convert UTC dates on the server side into the client's timezone using the minutes offset?

Create a DateTimeOffset that represents that moment in time. For example:

// From your database.  Make sure you specify the UTC kind.
DateTime utc = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc);

// From JavaScript
int offsetMinutes = 420;

// Don't forget to invert the sign here
TimeSpan offset = TimeSpan.FromMinutes(-offsetMinutes);

// The final result
DateTimeOffset dto = new DateTimeOffset(utc).ToOffset(offset);

Also, make sure you understand that the offset you retrieved from the client in JavaScript is not necessarily the correct offset to apply to your database date. When you get the offset, it has to be for a particular moment in time. Since many time zones change offsets for daylight saving time, you cannot assume that the offset you currently have is appropriate for any particular value in your database. Therefore, while the above code does what you asked, it is probably still not a good idea in general.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...