问题描述
我有以下代码,以en-us格式生成日期字符串。我想传入LCID(或本地化语言的等价值)来生成日期字符串的本地化版本。如何实现这一点?
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;
}
推荐答案
您可以使用第二个参数到功能,并使用您需要的任何语言/文化。 ..
You can use the second argument to the toString function and use any language/culture you need...
根据MSDN ...,您可以使用d格式而不是 ToShortDateString
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...
这篇关于如何使用CultureInfo生成本地化日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!