Reputation: 36773
Currently, I have a lot of operations on my website where I go:
if (auction.StartTime.Value <= DateTime.Now)
Then on my web application's _Layout.cshtml, I display the server time using:
<p id="time">@DateTime.Now.ToString("HH:mm")</p>
This correctly shows me the current server time, but I'd like to display this time according to where the user it. Sure I could do something like:
<p id="time">@DateTime.Now.ToGMT(-4).ToString("HH:mm")</p>
But this is maintanance nightmare. I'd have to set this GMT extension method everywhere. Maybe there's something cooked into the .NET framework?
How would you recommend I handle this?
Upvotes: 0
Views: 1291
Reputation: 18662
The easiest way would be to send unformatted (Invariant Culture format) value in UTC, re-create date objects on the client side (that is with JavaScript) and then use Globalize to properly format date and time according to local culture rules (and time zone but this one would be adjusted automatically).
The harder would require storing Time Zone information in user profile (or cookie) and force user to select valid time zone in the first place. Or alternatively read time zone offset on the client side (JavaScript Date's object getTimezoneOffset() function) and send it to server (via Ajax request for example) once per session. But this is not reliable (different time zones may have the same offset now but switch Daylight Saving on different dates).
Upvotes: 0
Reputation: 5828
Use this StackOverflow question for ways to send the timezone information from the user's browser to your server (the timezone information is not part of the browser traffic unfortunately, afaik).
Upvotes: 1
Reputation: 27627
The most important part of this is working out what the user's timezone is. Depending on the site this could be hardcoded (eg if it is only targeted at a single timezone) or part of the user's settings once they have logged in.
Once you know what the timezone is then something like TimeZoneInfo.ConvertTimeFromUtc may help with the actual conversion of the datetime.
Upvotes: 1
Reputation: 2628
You could embed the browser's current time in a hidden field (using the javascript GetDate() function) on first request then retrieve it on the server.
Upvotes: 0