带 CultureInfo 的 DayOfWeek.ToString()

我有密码:

DateTime.Now.DayOfWeek.ToString()

那给我的是一周的英语日的名字,我想有德语版本,如何在这里添加 CultureInfo 得到一周的德语日的名字?

97674 次浏览

DayOfWeek is an enumeration, so the ToString method on it is not culture sensitive.

You will need to write a function to convert the Enum value to a corresponding string in German, if you insist on using DayOfWeek:

string DayOfWeekGerman(DayOfWeek dow)
{


switch(dow)
{
case(DayOfWeek.Sunday)
return "German Sunday";
case(DayOfWeek.Monday)
return "German Monday";
...
}
}

A better approach is to use ToString from DateTime directly:

CultureInfo german = new CultureInfo("de-DE");
string dayName = DateTime.Now.ToString("dddd", german);
var culture = new System.Globalization.CultureInfo("de-DE");
var day = culture.DateTimeFormat.GetDayName(DateTime.Today.DayOfWeek);

You can use the DateTimeFormat.DayNames property of the german CultureInfo. For example:

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

This is the solution in Visual Basic

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


Return GermanCultureInfo.DateTimeFormat.GetDayName(DayOfWeek.Sunday)

The function of the solution is Obsolete by the way DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("de-DE"))

You can use this code to return your day name as same language

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

enter image description here note: DateTime returns a DayOfWeek Enumeration so I use the code to return from another Enumeration

I like this one:

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

And according to your question:

var culture = new System.Globalization.CultureInfo("de-DE");
var day = uiDateTime.GetDayOfWeek(culture);
DateTime date = DateTime.Today;


string day = date.ToString("dddd", new CultureInfo("es-MX"));


Console.WriteLine(day); //Jueves

only change "es-MX" for the region you want.