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; }
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”.
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.
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).
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With