Why does LocalTime display server time and not browser time?

I am probably doing something wrong, but cannot figure out why. I have a DateTime field in my DB storing UTC time

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

The PageLoad code looks like this:

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

      

The time I get is the local time in the US, not Europe. What should I do to display the local browser time?

Thank!

+1


source to share


4 answers


One method is to detect the client's timezone offset (in minutes) using javascript in the client's browser:

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

      



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

+4


source


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



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

+3


source


As some have written , the code runs on the server, so it makes sense that the applicable timezone is local to the server.

As with his suggestion to send UTC to the browser (which is fine when available, but not always an option), you should look into TimeZoneInfo if you are using .NET 3.5. This will allow you to convert between UTC and arbitrary time zones, including historical changes. (There is much more time than just "GMT + 5", etc.). The big difficulty lies in determining what time zone the user is in. You can usually get the current offset from UTC using JavaScript, but that doesn't give you all the information you need to align correctly. Sooner or later, you may have to have a setting for each user they are for.

+1


source


I don't think it would be wise to store time values ​​in your database depending on the time it is in the client browser.

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

For this reason, it is better to use server time (or better, as others have said, try and use UTC).

+1


source







All Articles