How to elegantly deal with timezones

Not that this is a recommendation, its more sharing of a paradigm, but the most agressive way I’ve seen of handling timezone information in a web app (which is not exclusive to ASP.NET MVC) was the following:

  • All date times on the server are UTC.
    That means using, like you said, DateTime.UtcNow.

  • Try to trust the client passing dates to the server as little as possible. For example, if you need “now”, don’t create a date on the client and then pass it to the server. Either create a date in your GET and pass it to the ViewModel or on POST do DateTime.UtcNow.

So far, pretty standard fare, but this is where things get ‘interesting’.

  • If you have to accept a date from the client, then use javascript to make sure the data that you are posting to the server is in UTC. The client knows what timezone it is in, so it can with reasonable accuracy convert times into UTC.

  • When rendering views, they were using the HTML5 <time> element, they would never render datetimes directly in the ViewModel. It was implemented as as HtmlHelper extension, something like Html.Time(Model.when). It would render <time datetime="[utctime]" data-date-format="[datetimeformat]"></time>.

    Then they would use javascript to translate UTC time into the clients local time. The script would find all the <time> elements and use the date-format data property to format the date and populate the contents of the element.

This way they never had to keep track of, store, or manage a clients timezone. The server didn’t care what timezone the client was in, nor had to do any timezone translations. It simply spit out UTC and let the client convert that into something that was reasonable. Which is easy from the browser, because it knows what timezone it is in. If the client changed his/her timezone, the web application would automatically update itself. The only thing that they stored were the datetime format string for the locale of the user.

I’m not saying it was the best approach, but it was a different one that I had not seen before. Maybe you’ll glean some interesting ideas from it.

Leave a Comment