Getting current culture day names in .NET

后端 未结 9 884
情书的邮戳
情书的邮戳 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 19:08

    This should also work nice.

        public static List<String> Days
        {
            var abbDayNames = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames;
    
            var days = new string[7];
            var firstDayOfWeek = (int)DayOfWeek.Monday;
            for (int i = 6; i>= 0; i--)
            {
                days[i] = abbDayNames[(firstDayOfWeek + i) % 7];
            }
    
            return new List<string>(days);
        }
    
    0 讨论(0)
  • 2021-01-11 19:10

    I am posting this as a separate answer as it really has nothing to do with my other answer (which may be useful to someone else in the future in another context.)

    As an alternative to codeka's solution, you can also do something like this (which would avoid having to hard code the en-us day names.)

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

    I meant to post this sooner but I am fighting a dying external hard drive...

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

    If you are getting day names based on dates, it doesn't matter what day the week starts on; DateTimeFormat.DayNames identifies Sunday as 0, as does DateTime, no matter if weeks start on Thursday or what have you. :)

    To get day name in English from a date:

    string GetDayName(DateTime dt)
    {
        return CultureInfo.InvariantCulture.DateTimeFormat.DayNames[(int)dt.DayOfWeek];
    }
    

    If for some reason you absolutely want to deal with the (magic value!) ints that underpin the DayOfWeek enumeration, just shift the index and take the modulus, hence mapping 0 => 6, 1 => 0, and so on:

    string GetDayName(int dayIndex)
    {
        return CultureInfo.InvariantCulture.DateTimeFormat.DayNames[(dayIndex + 6) % 7]; 
    }
    
    0 讨论(0)
提交回复
热议问题