Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce localized date string with CultureInfo

I have the following code that produces a date string in en-us format. I would like to pass in the LCID (or equivalent value for the localized language) to produce the localized version of the date string. How would I accomplish this?

public static string ConvertDateTimeToDate(string dateTimeString) {      CultureInfo culture = CultureInfo.InvariantCulture;     DateTime dt = DateTime.MinValue;      if (DateTime.TryParse(dateTimeString, out dt))     {         return dt.ToShortDateString();     }     return dateTimeString;   } 
like image 244
Keith Avatar asked Apr 27 '11 03:04

Keith


People also ask

How to format string date in c#?

The format must match with string date time or it throws FormatException. So to overcome this issue you can use string format array which has some possibilities. Suppose your date may be in format like “12/12/2015” or “12-12-2015”, here you need to pass string array with format like “MM/dd/yyyy” and “MM-dd-yyyy”.

What is fff in date format?

The "fff" custom format specifier represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.

What is en US date format?

The United States is one of the few countries that use “mm-dd-yyyy” as their date format–which is very very unique! The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).


1 Answers

You can use the second argument to the toString function and use any language/culture you need...

You can use the "d" format instead of ToShortDateString according to MSDN...

So basically something like this to return as Australian English:

CultureInfo enAU = new CultureInfo("en-AU"); dt.ToString("d", enAU); 

you could modify your method to include the language and culture as a parameter

public static string ConvertDateTimeToDate(string dateTimeString, String langCulture) {      CultureInfo culture = new CultureInfo(langCulture);     DateTime dt = DateTime.MinValue;      if (DateTime.TryParse(dateTimeString, out dt))     {         return dt.ToString("d",culture);     }     return dateTimeString;   } 

Edit
You may also want to look at the overloaded tryParse method if you need to parse the string against a particular language/culture...

like image 95
davidsleeps Avatar answered Oct 12 '22 22:10

davidsleeps