Get DateTime of the next nth day of the month

后端 未结 4 1419
慢半拍i
慢半拍i 2021-01-20 03:22

If given a date and a variable n, how can I calculate the DateTime for which the day of the month will be the nth Date?

For example, Today is the 17th of June. I wou

4条回答
  •  一向
    一向 (楼主)
    2021-01-20 03:31

    The spec is a little bit unclear about to do when today is the dayOfMonth. I assumed it was it to return the same. Otherwise it would just be to change to <= today.Day

    public DateTime FindNextDate(int dayOfMonth, DateTime today)
    {
        var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1);
        if(dayOfMonth < today.Day){ 
          nextMonth = nextMonth.AddMonths(1);
        }
        while(nextMonth.AddDays(-1).Day < dayOfMonth){
           nextMonth = nextMonth.AddMonths(1);
        }
        var month = nextMonth.AddMonths(-1);
        return new DateTime(month.Year, month.Month, dayOfMonth);
    
    }
    

提交回复
热议问题