Displaying culture specific date formats

Posted by Techie Cocktail | 6:20 PM | , | 0 comments »

Different countries use different date formats. Hard-coding different date formats in a multi-lingual application is definitely a bad choice. To display the date in the date format as used for a country, .net has ToShortDateString() function.

ToShortDateString() is culture-sensitive and outputs the date which is specific to the current culture set. Below example shows its use.


class Program
{
static void Main(string[] args)
{
//get the current culture and display its date format.
DateTime _date = DateTime.Now;
CultureInfo _currentCulture = Thread.CurrentThread.CurrentCulture;
Console.WriteLine("Current Culture: {0}: ", _currentCulture.Name);
Console.WriteLine(_date.ToShortDateString());

//set the current culture to french & display the french date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Console.WriteLine("French Culture: {0}", _date.ToShortDateString());

//set the current culture to italian & display the italian date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
Console.WriteLine("Italian Culture: {0}", _date.ToShortDateString());

//set the current culture to german & display the german date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
Console.WriteLine("German Culture: {0}", _date.ToShortDateString());

//set the current culture to spanish and display the spanish date format
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
Console.WriteLine("Spanish Culture: {0}", _date.ToShortDateString());

//set back to the original date format
Thread.CurrentThread.CurrentCulture = _currentCulture;
Console.WriteLine("Back to original Culture: {0}", _date.ToShortDateString());

Console.Read();
}
}

Get list of Cultures

If you are not aware of the culture names then you can use the following function to get the complete list of available cultures. You can use CurrentTypes enum that defines the types of culture lists that can be retrieved. The below example gets the list of all the cultures that ship with .NET Framework, including neutral and specific cultures, cultures installed in Windows OS and custom cultures created by the user.



static void GetAllCultures()
{
string specificCultureName = "";
CultureInfo[] arrCultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures);

foreach (CultureInfo ci in arrCultureInfo)
{
try
{
specificCultureName = CultureInfo.CreateSpecificCulture(ci.Name).Name;
}
catch { }

Console.WriteLine(ci.Name + ": " + specificCultureName + ": " + ci.EnglishName);
specificCultureName = "----";
}
Console.Read();
}

0 comments