获取每个月的固定的第n个星期几

以下例子获取每个月的第四个星期五

var StartDate = DateTime.Parse("05/23/2019");
var EndDate = DateTime.Parse("12/31/2019");

var Daily = 1;
for (var i = StartDate; i < EndDate; i = i.AddMonths(Daily))
{
    // Get the first of each month
    int month = i.Month;
    int year = i.Year;
    var FirstDay = new DateTime(year, month, 1);
    // Get the difference between first day and first Friday
    int difference = (int)DayOfWeek.Friday - (int)FirstDay.DayOfWeek;
    int adddays = difference >= 0 ? 21 : 28;
    int days = difference + adddays;
    var ForthFriday = FirstDay.AddDays(days);
    Console.WriteLine(ForthFriday.ToShortDateString());
}

结果:

posted @ 2019-04-26 17:05  Kyle0418  阅读(218)  评论(0编辑  收藏  举报