Getting current culture day names in .NET

2020-03-12 05:02发布

Is it possible to get the CurrentCulture's weekdays from DateTimeFormatInfo, but returning Monday as first day of the week instead of Sunday. And, if the current culture isn't English (i.e. the ISO code isn't "en") then leave it as default.

By default CultureInfo.CurrentCulture.DateTimeFormat.DayNames returns:

[0]: "Sunday"
[1]: "Monday"
[2]: "Tuesday"
[3]: "Wednesday"
[4]: "Thursday"
[5]: "Friday"
[6]: "Saturday" 

But I need:

[0]: "Monday"
[1]: "Tuesday"
[2]: "Wednesday"
[3]: "Thursday"
[4]: "Friday"
[5]: "Saturday" 
[6]: "Sunday"

标签: c# .net datetime
8条回答
我想做一个坏孩纸
2楼-- · 2020-03-12 05:27

One more idea, inspired by Josh's answer, using a Queue instead of shifting the array.

var days = CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "en")
{
    var q = new Queue<string>(days);
    q.Enqueue(q.Dequeue());
    days = q.ToArray();
}
查看更多
家丑人穷心不美
3楼-- · 2020-03-12 05:31

Since only one day is being moved, I solved this problem like this:

'the list is from Sunday to Saturday
'we need Monday to Sunday
'so add a Sunday on the end and then remove the first position
dayNames.AddRange(DateTimeFormatInfo.CurrentInfo.DayNames)
dayNames.Add(DateTimeFormatInfo.CurrentInfo.GetDayName(DayOfWeek.Sunday))
dayNames.RemoveAt(0)
查看更多
登录 后发表回答