Showing date time according to time zone

We should Localize and Globalize our software applications. Our users can see their native languages on the UI and also can see the various things are proper format as their local culture. For example date time, price format etc. But what about date time value? In the world there are many countries which are belongs to different time zones. If we are showing a date time on our application UI then we must take care of the local time. If we are showing the same date time for every users who are using from different time zones, that will not be a very user friendly!

// Show all time zones.
foreach (TimeZoneInfo zone in TimeZoneInfo.GetSystemTimeZones())
    Console.WriteLine(zone.DisplayName + "\n");

UTC date time

Now the question is if we want to show the local date time for every user of different time zones then in what format we should store the date time? One simple solution of this problem can be whenever we need to store date time in persistent layer then use Universal Time Coordinated (UTC). This is maintained as a stander date time through out the world. UTC and GMT are same. Every time zone has a offset. This offset is the time difference from UTC. This is called UTC offset. UTC offset can be positive or negative. Time zones who have positive UTC offset are actually before the UTC date time and UTC offset with negative are after the UTC offset. We need to calculate the local time of a time zone according the UTC date time and UTC offset of that particular time zone. For example ‘Indian Slandered Time’ (IST) is the time zone name of India and it has the UTC offset +5:30. When UTC date time is 01/01/2013 12:00 AM then Indian local time will be 01/01/2013 5:30 AM. So if we store our date time in UTC every time then it will be easy to convert the date time as per different time zone local time.

// Convert date time to UTC.
DateTime dtUtc = TimeZoneInfo.ConvertTimeToUtc(dtLocal, TimeZoneInfo.Local);
// Convert back to local date time at the time of retreving.
DateTime dtLocal = TimeZoneInfo.ConvertTimeFromUtc(dtUtc, TimeZoneInfo.Local);

In our web application we can also implement this functionality using JavaScript.

// Convert date time to UTC.
var dtUtc = dtLocal.toUTCString();
// Convert back to local date time at the time of retreving.
var dtLocal = new Date(dtUtc);

Happy coding…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s