I’ve got times saved in a sql database in utc format. I’m displaying those times on a gridview, however they are still UTC format. I’d like to convert them to the client’s browsers local time. The problem is that although I can get the timezone offset that is only for the current date/time. That offset could change if some of those dates in the future end up occuring during daylight savings time. I’m relatively new to web programming but it seems like what I need to do is run some Javascript as each entry binds to the gridview that somehow takes the C# datetimeoffset object and converts it to a local time. Or maybe that’s not possible?
Share
This can be done on the server side if you have a
TimeZoneInfoobject. You can use the staticConvertTimeFromUtc()method.In C#:
If you do not have the timezone on the server side things get tricky since javascript does not provide the client’s timezone (unless they are in the US, and even then only on some browsers). In this case, it may be best to force the user to select their current timezone and store it against their account. If this is being displayed to anonymous users, you should probably display in UTC by default and provide an option to refresh it for a selected timezone.
Update
There are several issues which appear when trying to automatically determine a user’s timezone.
The javascript function
getTimezoneOffset()may initially sound like a good idea, but since there are multiple timezones with the same offset, this is not a unique value. The difference between many of these non-unique zones is their implementation of daylight saving time.If, however, your user base is located primarily in the US and uses IE, Chrome, Safari, or Firefox, than you can use the
toString()method on aDateobject to obtain the timezone. These browsers append the timezone to the date string in different ways. Outside the US, the timezone is not included in all browsers (though some may still show it).With some parsing, you can now determine the timezone for all your American users. For everyone else you can display the time in UTC (with a notice to that effect).