LeJeune
LeJeune

Reputation: 950

Why LocalTime displays server time and not browser time?

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!

Upvotes: 1

Views: 4298

Answers (4)

J c
J c

Reputation: 6413

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.

Upvotes: 5

Harry Lime
Harry Lime

Reputation: 29576

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).

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1501163

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.

Upvotes: 1

some
some

Reputation: 49612

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)

Upvotes: 3

Related Questions