Friday, May 31, 2013

Ain't Nobody Got Time For That!

Time Zones. To most they are a cause of confusion as to why TV shows are on at different times. To some they are the cause of much pain and torment trying to build an application for people across the country and world. Fear not those of you that are of the .NET world. I have the solution for you. That solution is the following, timezoneinfo. This simple class can convert datetime objects to any timezone that you want. You simply just need the following code.

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");DateTime PstDateTime = TimeZoneInfo.ConvertTime(DateTime.Now, tzi);

Now you can take your server time and turn it into any time that you want. And it doesn't have to be just now either, it can be any time that you give it. Just pass the zone id and you are good to go. 
Need a quick list of timezones? 
@Html.DropDownListFor(x => x.TimeZoneId, new SelectList(TimeZoneInfo.GetSystemTimeZones(), "Id", "DisplayName"))
There you go. Just slap that into your cshtml and you have a dropdown with all the timezones in the world. Did I mention that this also handles Daylight Savings Time? Because it does. It knows when to fall back, and spring forward. It also handles places like Arizona that have no DST at all. It really is an awesome class.

No comments:

Post a Comment