I have an ASP.NET MVC app that stores all SQL DateTime in UTC, so that the time is consistent regardless of time zone that the client is hitting the site from.
Now, I want to re-display the correct time to the user, so any time I display a time in my View I use:
timeVariable.ToLocalTime();
However, .ToLocalTime() is based on the server, not the client.
Do I need to handle this in JavaScript on the client?
I probably could pass the time zone as part of the request and have the controller handle the offest, but I am assuming there is a better way to do this. Or isn't there?
Thanks in advance for any help!
-Matt
Almost all sites that I have seen that translate time to local time ask the user to specify his or her timezone when creating an account. Gmail is one example but there are many others.
I've found that many solutions trying to use javascript or reverse-lookup on the IP address are prone to failure and edge cases.
In addition to Derrick's answer, "Append 'UTC' to the string before converting it to a date in javascript." Convert UTC date time to local date time using JavaScript
The UTCTime can be converted automatically to local time.
For Asp.Net MVC + jQuery I've created a DisplayTemplate and script to help with this.
Model class:
DisplayTemplate: Views\Shared\DisplayTemplates\UTCTime.cshtml
Add to Views\Shared_Layout.cshtml, or to your View:
Clean it up a little of course, it's a bit verbose so you can see what's going on.