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.

Anyway, in the meantime I have resorted to the tried and true way of just passing across the timezone offset of the browser via javascript. Read on to see how I have handled the conversion of times on reports to local time.

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:

DateTime.Now.ToUniversalTime();

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.

Here’s how I handle it on the client side using a snippet of javascript:

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.

BondiGeek