Getting current culture day names in .NET

后端 未结 9 883
情书的邮戳
情书的邮戳 2021-01-11 18:32

Is it possible to get the CurrentCulture\'s weekdays from DateTimeFormatInfo, but returning Monday as first day of the week instea

相关标签:
9条回答
  • 2021-01-11 18:46

    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)
    
    0 讨论(0)
  • 2021-01-11 18:47

    You can use custom cultures to create a new culture based off an existing one. To be honest, though, I'd say that's probably a bit heavy-handed. The "simplest" solution may just be something like:

    public string[] GetDayNames()
    {
        if (CultureInfo.CurrentCulture.Name.StartsWith("en-"))
        {
            return new [] { "Monday", "Tuesday", "Wednesday", "Thursday",
                            "Friday", "Saturday", "Sunday" };
        }
        else
        {
            return CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
        }
    }
    
    0 讨论(0)
  • 2021-01-11 18:56

    DatetimeFormatInfo.GetDayName obviously, with a foreach on each DayOfWeek in the order you want. :) No hack, simple and effective

    0 讨论(0)
  • 2021-01-11 18:57

    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();
    }
    
    0 讨论(0)
  • 2021-01-11 19:05

    You can Clone the current culture which gets a writable copy of the CultureInfo object. Then you can set the DateTimeFormat.FirstDayOfWeek to Monday.

    CultureInfo current = CultureInfo.Current;
    CultureInfo clone = (CultureInfo)current.Clone();
    
    clone.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;
    

    The above clone will now treat Monday as the first day of the week.

    EDIT

    After re-reading your question I don't think this will do what you're expecting. The DayNames will still return in the same order regardless of the FirstDayOfWeek setting.

    But I'll leave this answer up as community wiki in case someone comes across this question in the future.

    0 讨论(0)
  • 2021-01-11 19:05

    Another simple solution:

    var dayNames = Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames.ToList();
    
    if (Culture.DateTimeFormat.FirstDayOfWeek == DayOfWeek.Monday)
    {
        dayNames.Add(dayNames[0]);
        dayNames.RemoveAt(0);
    }
    
    0 讨论(0)
提交回复
热议问题