Using DateTimeFormatInfo to localise date and time in .NET C#
August 13, 2014 Leave a comment
Every programmer loves working with dates and time, right? Whether or not you like it it is inevitable to show the dates in a format that the viewer understands. You should not show dates presented according to the US format in Japan and vice versa.
The DateTimeFormatInfo class includes a range of useful properties to localise date and time. The entry point to the DateTimeFormatInfo class is CultureInfo. E.g. if you’d like to format a date according to various cultures – Swedish, Hungarian and German – then you can do it as follows:
CultureInfo swedishCulture = new CultureInfo("sv-SE");
DateTimeFormatInfo swedishDateFormat = swedishCulture.DateTimeFormat;
CultureInfo hungarianCulture = new CultureInfo("hu-HU");
DateTimeFormatInfo hungarianDateFormat = hungarianCulture.DateTimeFormat;
CultureInfo germanCulture = new CultureInfo("de-DE");
DateTimeFormatInfo germanDateFormat = germanCulture.DateTimeFormat;
DateTime utcNow = DateTime.UtcNow;
string formattedDateSweden = utcNow.ToString(swedishDateFormat.FullDateTimePattern);
string formattedDateHungary = utcNow.ToString(hungarianDateFormat.FullDateTimePattern);
string formattedDateGermany = utcNow.ToString(germanDateFormat.FullDateTimePattern);
…which yields the following formatted dates:
- den 12 juni 2014 20:08:30
- 2014. június 12. 20:08:30
- Donnerstag, 12. Juni 2014 20:08:30
DateTimeFormatInfo includes patterns for other types of date representations, such as MonthDayPattern, LongDatePattern etc.
You can also get the names of the days and months:
string[] swedishDays = swedishDateFormat.DayNames; string[] germanDays = germanDateFormat.DayNames; string[] hungarianDays = hungarianDateFormat.DayNames; string[] swedishMonths = swedishDateFormat.MonthNames; string[] hungarianMonths = hungarianDateFormat.MonthNames; string[] germanMonths = germanDateFormat.MonthNames;
You can do a lot more with DateTimeFormatInfo:
- The Calendar associated with the culture
- The date separator
- Abbreviated month and day names
- First day of the week
…and more. I encourage you to inspect the available properties of the DateTimeFormatInfo object with IntelliSense in Visual Studio.
Read all posts related to Globalisation in .NET here.