Working on a project this week I needed to pay close attention to the Timezone offset for data displayed in reports on a web application.
Unfortunately the HttpBrowserCapabilities class in asp.net doesn’t offer us the Timezone or Timezone offset of the browser. If anyone knows where it might be hidden away I would love to know.
I have made it a habit to store all times in UTC on the database as it’s gives us the freedom to convert to local times and is a good frame of reference.
So in this particular application every database update or modification just converts to UTC using the extension method of the DateTime class:
Of course this means when we want to pull data out of the database and use it on reports or for display we need to convert back to the local timezone so it makes sense.
var d = new Date(); var timezoneOffset = d.getTimezoneOffset() / 60;
This gives me a current timezone offset of –10 (hours) down here in Sydney
Now on the Server side when a request is made for data I need to pass across that timezone offset and use it to convert from UTC to Local time like so:
timezoneOffset = timezoneOffset * -1; MyDate.AddHours(timezoneOffset);
First we need to reverse the offset from –10 to 10 so we multiply by –1. Then just use the AddHours extensions method passing in the offset value and voila! we have our dates and times converted from UTC to Local time.