DateTime.Now.DayOfWeek.ToString()与CultureInfo


70

我有代码:

DateTime.Now.DayOfWeek.ToString()

那就是我的英文星期几名称,我想拥有德语版本,如何在此处添加CultureInfo以获得德语的星期几名称?

Answers:



14

您可以使用DateTimeFormat.DayNames德语的属性CultureInfo。例如:

CultureInfo german = new CultureInfo("de-DE");
string sunday = german.DateTimeFormat.DayNames[(int)DayOfWeek.Sunday];

6

这是Visual Basic中的解决方案

Dim GermanCultureInfo As Globalization.CultureInfo = New Globalization.CultureInfo("de-DE")

Return GermanCultureInfo.DateTimeFormat.GetDayName(DayOfWeek.Sunday)

该解决方案的功能已过时 DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("de-DE"))


5

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);

1
本文提到了DateTime.ToString(String)或的DateTime.ToString(String, IFormatProvider)本地化名称-无需为此编写函数。
伊恩·普格斯利

2

我喜欢这一个:

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);

0

您可以使用此代码以相同的语言返回您的日期名称

CultureInfo myCI = new CultureInfo("ar-EG");   
MessageBox.Show(myCI.DateTimeFormat.GetDayName(DayOfWeek.Friday));

在此处输入图片说明 注意:DateTime返回一个DayOfWeek枚举,所以我使用代码从另一个枚举返回

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.