C# format date times for different locals (localization and globalization), DateTimeFormatInfo

Working on a project recently I found we were presenting date/time data to a variety of users in various countries. Each country uses it's own date/time formatting. Here in the US it's often MM/dd/yyyy, however in Europe it's often dd/MM/yyyy and in Asia they don't even have the slashes they use special characters that designate year, month, and day. At first we were going to come up with localized versions of all the possible date/time combinations you can display (June 6th, 1977, 6/25/77, etc) but Microsoft has an even better solution already in place.

static void Main( string[] args )
{
         DateTime dt = DateTime.Now;

         // let's create some different date times for different cultures

         // JAPANESE
         CultureInfo culture = new CultureInfo("ja-JP");
         DateTimeFormatInfo formatInfo = culture.DateTimeFormat;
         String time = dt.ToString( formatInfo.FullDateTimePattern, culture );
         MessageBox.Show( time );

         // ENGLISH
         culture = new CultureInfo( "en-US" );
         formatInfo = culture.DateTimeFormat;
         time = dt.ToString( formatInfo.FullDateTimePattern, culture );
         MessageBox.Show( time );

         // SIMPLIFIED CHINESE
         culture = new CultureInfo( "zh-CN" );
         formatInfo = culture.DateTimeFormat;
         time = dt.ToString( formatInfo.FullDateTimePattern, culture );
         MessageBox.Show( time );

         // FRENCH
         culture = new CultureInfo( "fr-FR" );
         formatInfo = culture.DateTimeFormat;
         time = dt.ToString( formatInfo.FullDateTimePattern, culture );
         MessageBox.Show( time );

         Console.ReadKey();

}

Looking at the code, we take the current date time and use the format string from the DateTimeFormatInfo to convert the current date time into the date time of the specified culture. In this example I'm using the FullDateTimePattern, but the DateTimeFormatInfo class has a many different formats you can use.

You can read about all the different formats at MSDN.


I hope this example helps you easily get date/times formatted into the various cultures. I know I've found it quite useful.

Comments

Anonymous said…
Yes but they are displaying the same time in different languages. Whereas it should display the actual time in different countries how would you tackle that

Saurabh
(myemail.co.in)

Popular posts from this blog

String.Replace vs Regex.Replace

C# Producer Consumer using Rabbit MQ

C# Form Application in Kiosk Mode/Fullscreen