Localized hours of the day

by Scosby Thursday, February 19, 2009

This code snippet is great for generating culturally correct (formatted) strings representing all 24 hours of the day. It returns a List of Strings localized to the current culture (for en-US this is 12:00 AM, 1:00 AM, 2:00 AM, ect)

private List<String> GetFormattedLocalHours()
{
     List<String> times = new List<String>(23);
     for (Int32 i = 0; i < 24; i++)
     {
           System.Globalization.
DateTimeFormatInfo dtfi = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
           DateTime temp = new DateTime(2008, 1, 1, i, 0, 0, DateTimeKind.Local);
           times.Add(temp.ToString(dtfi.ShortTimePattern));
     }
     return times;
}

The key point worth noting here is the use of the CultureInfo class' CurrentCuture.DateTimeFormat property. This property returns a DateTimeFormatInfo object that we can use to get the format string appropriate for the CurrentCulture's local from the DateTimeFormatInfo.ShortTimePattern property. Pass this property's value to a DateTime.ToString() instance as the format pattern and you'll get a localized (format) string. Amazing!

What this means is that for any "localized" application,  there is NO excuse for putting AM or PM in front of the numbers 1-12. It takes you very little code to generate culturally correct times of the day for any culture supported by the .NET Framework. Many cultures around the world strictly use a 24-hour clock and thus use "14:00" to represent "2:00 PM". So don't be lazy and, more importantly, culturally insensitive by forcing users in other cultures to read DateTime values in a format other than what they are expecting.

Tags: ,

Technology | Programming