Aug
20
2008

SPRegionalSettings.GlobalTimeZones - How to build world clock / get time zones information in SharePoint

Ok, you probably do not want to create world clock web part from scratch. Many free ones over Internet. Not to mention the very popular world clock web part from "bamboo Solutions".

But if you really want to create one by yourself for whatever the reason is, or you just want show the local time for employees working in different cities around the world (in their profile page, maybe). It can be done easily without to use any external web services, or hack your way through windows registry to get time zones list.

Yes, thanks to SharePoint OM. You can get all the information you want from Microsoft.SharePoint.dll

SPRegionalSettings.GlobalTimeZones

It returns you a collection of SPTimeZones objects used in Windows SharePoint Services.

SPTimeZoneCollection timeZoneColl = SPRegionalSettings.GlobalTimeZones;
foreach (SPTimeZone tz in timeZoneColl)
{
    DateTime currentLocalDateTime = DateTime.Now;
    DateTime currentDestDateTime = tz.UTCToLocalTime(currentLocalDateTime.ToUniversalTime());
        Console.WriteLine("ID: {0}, DateTime: {1}, Description: {2}", tz.ID, currentDestDateTime.ToString(), tz.Description);
}

In above code sample, it loop through each SPTimeZone inside SPTimeZoneCollection. Writes ID, current date time (in local server date time format) and description in console.

This is what you will get

James Tsai .Net SharePoint VSTO C# ASP.NET Blog - SPRegionalSettings GlobalTimeZones Code Sample

As you can see, my local time in Sydney, Australia is Thursday, August 21, 2008 4:01pm. And time in Tokyo, Japan is 08/21/2008 3:01pm. In Auckland, New Zealand is 08/21/2008 6:01pm. Which are correct!

//This line of code converts SPTimeZone object from UTC to your local time
DateTime currentDestDateTime = tz.UTCToLocalTime(currentLocalDateTime.ToUniversalTime());

Basically that's all you need to create world clock web part, or date time conversion control in SharePoint site. You can either have GlobalTimeZones collection as drop down list for user to select the time zone for displaying date time. Or you can create a SharePoint list mapping between cities name with time zone ID in GolbalTimeZones collection.

blog comments powered by Disqus