Getting current culture day names in .NET

后端 未结 9 939
情书的邮戳
情书的邮戳 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条回答
  •  萌比男神i
    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]; 
    }
    

提交回复
热议问题