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?
The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC.
(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.
A UTC offset is the difference in hours and minutes between a particular time zone and UTC, the time at zero degrees longitude. For example, New York is UTC-05:00, which means it is five hours behind London, which is UTC±00:00.
Save this answer. Show activity on this post. The maximum difference is at least 26 hours, as there are time zones for GMT-12 all the way to GMT+14. With DST, that may go up to 27 hours.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With