Wednesday 22 September 2010

C#: Cultures


Cultures are things you probably won't come across for general projects unless you are dealing with support for multiple viewing countries. This mainly includes: Dates, times and currencies.

For example, When parsing (using Parse/TryParse) a DateTime object, it assumes the DateTime is in US format... so when we come to use this, we'll notice our days and months are the wrong way round!


Parsing a string in a DateTime object with a UK Culture
using System.Globalization;   // For access to culture objects
 
 
private DateTime ParseDate(string IncomingDate)
{
    CultureInfo ukCulture = new CultureInfo("en-GB");
    DateTime parsedDate = new DateTime();
 
    DateTime.TryParse(IncomingDate, ukCulture.DateTimeFormat, DateTimeStyles.None, out parsedDate);
 
    return parsedDate;
}



An implicit example
DateTime dateObj = DateTime.Parse(inputString, new CultureInfo("en-GB"));



We can also apply culture globally across a whole application by setting culture settings in the Web.config file. In the following snippet, we have Culture and UICulture. The former refers to how DateTime objects and currencies are parsed etc. Using a en-GB culture will ensure these all use UK currencies and formatting. The latter determines which resource files are used for the UI.


Setting the culture globally in the Web.config
<globalization uiCulture="en-GB" culture="en-GB" />

No comments: