How to do timezones in ASP.NET MVC?

For this purpose, you should definitely be storing your timestamps in UTC in the database.

When you need to display a date from the database on your site, you can do this:

DateTime stamp = /* get datetime from the database here, make sure you
                    use the constructor that allows you to specify the 
                    DateTimeKind as UTC. */

//E.g.
//DateTime stamp = new DateTime(2009, 12, 12, 12, 12, 12, DateTimeKind.Utc);

timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(" /* users time zone here */"); 
var convertedTime = TimeZoneInfo.ConvertTime(stamp, timeZoneInfo);

//Print out the date and time
//Console.WriteLine(convertedTime.ToString("yyyy-MM-dd HH-mm-ss")); 

The list of timezones is already available in .Net, so you can see this post on how to enumerate them. For ASP.Net MVC, instead of printing the time out, you would want to assign the converted datetime to a property of your model class so your View could use it for display.


I cannot stress how important it is to use UTC for storage and processing for any application you write. Even if you know the application will ever only be used in a single timezone it is still much easier to work with UTC than a local timezone because of daylight saving time issues.

There's really nothing special you need to do at the database level. Just create a normal datetime column, but make sure it is documented clearly that the column is assumed to be UTC.

I'll be honest, asp.net isn't my expertise, but I'm thinking you could obtain the timezone from the client request somehow. Actually, because the daylight saving time rules can be pretty obscure depending on the region it might be better to use a java script that calculates the UTC offset and use that to make the conversions. Even after the Energy Policy Act of 2005 there are still some exceptions to the DST rules that would rather hard to deal with on the server side. However, I think you're idea of allowing the client to set their own timezone would work well in most cases.