How to get the name of each day in next month?

后端 未结 5 503
无人共我
无人共我 2021-01-23 01:35
DateTime dt = new DateTime();
dt = DateTime.Now.AddMonths(1);
int x = DateTime.DaysInMonth(dt.Year, dt.Month);
MessageBox.Show(x.ToString());  // works ok - 31
         


        
5条回答
  •  情歌与酒
    2021-01-23 01:41

    You can also leverage Enumerable.Range and LINQ (and the DaysOfWeek enum)

    DateTime dt = DateTime.Now.AddMonths(1);
    
    Enumerable.Range(1, DateTime.DaysInMonth(dt.Year, dt.Month))
        .Select(dayNumber => new DateTime(dt.Year, dt.Month, dayNumber))
        .Select(dayName => dayName.DayOfWeek.ToString()).ToList()
        .ForEach(day => MessageBox.Show(day));
    

    The two .Select()s can be merged but I kept them separated for readability.

提交回复
热议问题