Date and Time format strings in .NET – CultureInfo

As mentioned in my last post, the IFormatProvider interface in the context of DateTime is mostly used for formatting a DateTime to a specific representation and for parsing a string into a DateTime instance.

Overloads that do not specify IFormatProvider

So, what happens when overloads of ToString and the different Parse methods (Parse, TryParse, ParseExact and TryParseExact) that don’t take an IFormatProvider instance are used?

To answer this, I will ask this question: what would the console output of the following lines of code?

DateTime dt = new DateTime(2011, 11, 21, 12, 34, 56);
Console.WriteLine(dt);

The answer is – it depends. It depends on the configured locale of the account that the application is executing under (see the Regional Settings and what the different Date and Time formats are configured as). The locale will determine what culture is used in.

So, if the user is in England, the result could be:

21/11/2011 12:34:56

If, however, the user is in the United States, the result could be:

11/21/2011 12:34:56 PM

As I have demonstrated, the CultureInfo instance associated with the current thread is the one used. Depending on the application context, either the Thread.CurrentCulture or Thread.CurrentUICulture culture would be used.

For this reason, both Thread.CurrentCulture and Thread.CurrentUICulture should usually be changed at the same time to the same CultureInfo.

Specifying an IFormatProvider

By specifying an IFormatProvider you can be explicit about over how DateTime instances get formatted and how strings get parsed into DateTime instances.

For example, here is how you would explicitly format a DateTime with a US culture:

DateTime dt = new DateTime(2011, 11, 21, 12, 34, 56);
Console.WriteLine(dt.ToString(CultureInfo.GetCultureInfo("en-US")));

And for the British version:

DateTime dt = new DateTime(2011, 11, 21, 12, 34, 56);
Console.WriteLine(dt.ToString(CultureInfo.GetCultureInfo("en-GB")));

The most amount of control would come with format strings, these do however interact with the culture – this will be covered in a future post.

Some asides

You can create your own cultures using … See How to: Create Custom Cultures on MSDN and the CultureAndRegionInfoBuilder class.

Some locale settings can be changed – I will discuss some of that in a future post.

Here is good Microsoft FAQ about locales and languages – http://msdn.microsoft.com/en-us/goglobal/bb688174.

Leave a Reply

Your email address will not be published. Required fields are marked *