我有代码:
DateTime.Now.DayOfWeek.ToString()
那就是我的英文星期几名称,我想拥有德语版本,如何在此处添加CultureInfo以获得德语的星期几名称?
Answers:
var culture = new System.Globalization.CultureInfo("de-DE");
var day = culture.DateTimeFormat.GetDayName(DateTime.Today.DayOfWeek);
您可以使用DateTimeFormat.DayNames
德语的属性CultureInfo
。例如:
CultureInfo german = new CultureInfo("de-DE");
string sunday = german.DateTimeFormat.DayNames[(int)DayOfWeek.Sunday];
DayOfWeek
是枚举,因此其ToString
上的方法对文化不敏感。
您需要编写一个函数来枚举值转换为在德国的一个相应的字符串,如果你坚持使用DayOfWeek
:
string DayOfWeekGerman(DayOfWeek dow)
{
switch(dow)
{
case(DayOfWeek.Sunday)
return "German Sunday";
case(DayOfWeek.Monday)
return "German Monday";
...
}
}
更好的办法是使用ToString
来自DateTime
直接:
CultureInfo german = new CultureInfo("de-DE");
string dayName = DateTime.Now.ToString("dddd", german);
我喜欢这一个:
public static class DateTimeExtension
{
public static string GetDayOfWeek(this DateTime uiDateTime, CultureInfo culture = null)
{
if (culture == null)
{
culture = Thread.CurrentThread.CurrentUICulture;
}
return culture.DateTimeFormat.GetDayName(uiDateTime.DayOfWeek);
}
}
并根据您的问题:
var culture = new System.Globalization.CultureInfo("de-DE");
var day = uiDateTime.GetDayOfWeek(culture);
DateTime.ToString(String)
或的DateTime.ToString(String, IFormatProvider)
本地化名称-无需为此编写函数。