Converting UTC Dates to a user specified time zone in C#/ASP.NET
Posted 1/12/2009 4:43:26 p.m. by Daniel in Computers
I have been pissing around with this one for months – when someone posts anything on Kustom Page, the date gets stored in UTC, which is all good for storing date. But, of course, when they want to display a date on their site, say a blog post date, it comes up with that UTC date, which, if you live in New Zealand like I do, is 12 hours behind when you actually posted it. And who posts blogs at 3am in the morning?
My aim was always to allow users to set their own time zone, and then pass the dates through a convertor wherever it will be displayed on the screen. Sounds easy right? Actually it is. After reading this post at least.
So I wrote up a quick little class that takes care of that conversion, and can also return you a list of time zones
public class TimezoneConvertor
{
public static DateTime Convert(DateTime UTCDate, string TimezoneID)
{
return TimeZoneInfo.ConvertTimeFromUtc(UTCDate,
TimeZoneInfo.FindSystemTimeZoneById(TimezoneID));
}
public static string Convert(DateTime UTCDate, string TimezoneID, string Format)
{
return TimeZoneInfo.ConvertTimeFromUtc(UTCDate,
TimeZoneInfo.FindSystemTimeZoneById(TimezoneID)).ToString(Format);
}
public static ReadOnlyCollection GetTimeZones()
{
return TimeZoneInfo.GetSystemTimeZones();
}
}
Obviously you’ll need to know the users time zone, which you could store in the database, or wherever you normally store your users settings.
For those of you using ASP.NET MVC, here’s a quick little conversion method to a list of SelectItems
public static ListTimeZoneSelectList(string SelectedName) { var timeZones = TimezoneConvertor.GetTimeZones(); var listOfTimeZones = new List (); foreach (var zone in timeZones) { var item = new SelectListItem(); item.Text = zone.DisplayName; item.Value = zone.Id; if(item.Text == SelectedName) item.Selected = true; listOfTimeZones.Add(item); } return listOfTimeZones; }