KnowDotNet NetRefactor

Adjusting for Culture

by William Ryan
Print this Article Discuss in Forums

Depending on the audience that you write your applications for, you may well need to accomodate users that 'ain't from round here'.  If you test for a specific date for instance, and the computer is running with different localization settings than the machine you tested on, you may have some issues.  To deal with this, you can specify a specific formatter (although using a more sophisiticated Localization technique is probably in store if you are doing anything of any complexity) and set the CurrentThread.CurrentCultureInfo accordingly.  To use this effectively, all you really need to know is the CultureInfo formatter and off you go.  There's a WHOLE lot more than what I'm illustrating here but this coupled with the above link is all you need to handle basic scenarios for just about every country you may be sitting in:

private void SetFormats()
{
  
string dateTime = string.Empty;
    DateTime rightNow = DateTime.Now;
    Thread.CurrentThread.CurrentCulture =
new CultureInfo("ar-SA");
    Debug.WriteLine(rightNow.ToString("d"));
    Thread.CurrentThread.CurrentCulture =
new CultureInfo("fr-FR");
    Debug.WriteLine(rightNow.ToString("d"));  
//surrender
   Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-BE");
    Debug.WriteLine(rightNow.ToString("d"));
    Thread.CurrentThread.CurrentCulture =
new CultureInfo("en-US");
    Debug.WriteLine(rightNow.ToString("d"));
    Thread.CurrentThread.CurrentCulture =
new CultureInfo("en-GB");
    Debug.WriteLine(rightNow.ToString("d"));
    Thread.CurrentThread.CurrentCulture =
new CultureInfo("es-ES");
    Debug.WriteLine(rightNow.ToString("d"));
}

And of course the results:

29/07/25
13/09/2004
13/09/2004
9/13/2004
13/09/2004
13/09/2004
The program '[1276] CultureStuff.exe' has exited with code 0 (0x0).


While this is certainly pretty easy to perform, it's nice to have available becuase it's pretty easy to overlook date formats for different cultures and it really takes very little effort to handle it.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing