views:

934

answers:

4

I am probably doing something wrong -- but cant figure why. I have a DateTime field in my DB keeping a UTC time

My server is in the US, and the browser is in Europe.

The PageLoad Code is as follow:

DateTime t = DateTime.SpecifyKind((DateTime)rdr["startTime"], DateTimeKind.Utc);
label1.Text = t.ToLocalTime().ToString();

The time displayed I get is US localtime and not Europe. What should I do to display the browser's localtime?

Thanks!

+3  A: 

One technique is to detect the client timezone offset (in minutes) using javascript on the client browser:

alert((new Date()).getTimezoneOffset();

This can then be sent back to the server and stored in the session or a cookie and used to offset the UTC dates displayed to them. Alternatively, another technique is to have user profiles where they can specify their timezone.

J c
+3  A: 

toLocalTime is executed on your server, not the browser. If you want to convert the dates on the server side, you must get the timezone the user is in (there are at least 3 timezones here in Europe, 6 if you count the summer time....)

One approach is to send the UTC times to the client, and then use some javascript to convert it to the users local time (the Date object in javascript knows what the users system is set at)

some
A: 

As some wrote, the code is being executed on the server - so it makes sense that the timezone which is applied is the one which is local to the server.

As well as his suggestion of sending UTC to the browser (which is good when it's available, but isn't always an option) you should look into TimeZoneInfo if you're using .NET 3.5. That will let you convert between UTC and arbitrary timezones, including historical changes. (There's a lot more to timezones than just "GMT+5" etc.) The big difficulty is working out what timezone the user is actually in. You can generally get the current offset from UTC with JavaScript, but that doesn't give you all the information you need to get it right consistently. Sooner or later you may well have to have a per-user setting for which timezone they're in.

Jon Skeet
+1  A: 

I don't think it's wise to store time-values in your database based on what time it is in the client's browser.

If you have many clients in many different time zones and the stored information is ever collated or shared - the order of events will be incorrect. 10:16 GMT is before 10:30 US-Eastern time, for example.

For this reason it's better to use the server time (or better again as has been said by the others - try and use UTC).

Harry Lime
My advice is to always use UTC, especially if your local time have summer time / daylight savings. With UTC every point in time have a unique value and it is easy to calculate the time between two dates. And when you want a loacal time, just use the right query or convert it at the client.
some