在.NET中获取当前的文化日名称

Chr*_*tow 9 .net c# datetime

是否有可能CurrentCulture从工作日开始DateTimeFormatInfo,但周一作为一周的第一天而不是周日返回.并且,如果当前文化不是英语(即ISO代码不是"en"),则将其保留为默认值.

默认CultureInfo.CurrentCulture.DateTimeFormat.DayNames返回:

[0]: "Sunday"
[1]: "Monday"
[2]: "Tuesday"
[3]: "Wednesday"
[4]: "Thursday"
[5]: "Friday"
[6]: "Saturday" 
Run Code Online (Sandbox Code Playgroud)

但是我需要:

[0]: "Monday"
[1]: "Tuesday"
[2]: "Wednesday"
[3]: "Thursday"
[4]: "Friday"
[5]: "Saturday" 
[6]: "Sunday"
Run Code Online (Sandbox Code Playgroud)

Dea*_*ing 10

您可以使用自定义文化来创建基于现有文化的新文化.说实话,我会说这可能有点笨拙."最简单"的解决方案可能就像:

public string[] GetDayNames()
{
    if (CultureInfo.CurrentCulture.Name.StartsWith("en-"))
    {
        return new [] { "Monday", "Tuesday", "Wednesday", "Thursday",
                        "Friday", "Saturday", "Sunday" };
    }
    else
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*osh 6

您可以克隆当前文化,该文化获取CultureInfo对象的可写副本.然后,您可以将DateTimeFormat.FirstDayOfWeek设置为Monday.

CultureInfo current = CultureInfo.Current;
CultureInfo clone = (CultureInfo)current.Clone();

clone.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;
Run Code Online (Sandbox Code Playgroud)

以上clone将把星期一视为一周的第一天.

编辑

在重新阅读你的问题后,我认为这不会做你期望的事情.无论FirstDayOfWeek设置如何,DayNames仍将以相同的顺序返回.

但是我将把这个答案作为社区wiki留下,以防将来有人遇到这个问题.


Jos*_*osh 5

我将此作为一个单独的答案发布,因为它与我的其他答案无关(在未来的另一个环境中,这可能对其他人有用.)

作为codeka解决方案的替代方案,您还可以执行类似的操作(这样可以避免对en-us日名称进行硬编码.)

string[] dayNamesNormal = culture.DateTimeFormat.DayNames;
string[] dayNamesShifted = Shift(dayNamesNormal, (int)DayOfWeek.Monday);

// you probably wanna add some error checking here.
// this method shifts array left by a specified number
// of positions, wrapping the shifted elements back to
// end of the array
private static T[] Shift<T>(T[] array, int positions) {
    T[] copy = new T[array.Length];
    Array.Copy(array, 0, copy, array.Length-positions, positions);
    Array.Copy(array, positions, copy, 0, array.Length-positions);
    return copy;
}
Run Code Online (Sandbox Code Playgroud)

我的意思是尽快发布,但我正在与一个垂死的外置硬盘打架......


Chr*_*tow 5

受Josh的回答启发,另一个想法是使用Queue而不是移动数组。

var days = CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "en")
{
    var q = new Queue<string>(days);
    q.Enqueue(q.Dequeue());
    days = q.ToArray();
}
Run Code Online (Sandbox Code Playgroud)