检查DateTime大于C#

时间:2019-06-19 15:12:10

标签: c#

我正在尝试输出包含结束日期在内的日期序列。由于某些原因,如果开始日期的Day部分大于End Date的Day部分,则不包括结束日期。下面是我的示例输出代码,

static void Main(string[] args)
    {
       var StartDate = DateTime.Parse("06/28/2019");
        var EndDate = DateTime.Parse("09/27/2019");

        var Daily = 1;
        for (var i = EndDate; i > StartDate; 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.Monday - (int)FirstDay.DayOfWeek;
            int adddays = difference > 0 ? 21 : 28;
            int days = difference + adddays;
            var ForthTues = FirstDay.AddDays(days);
            Console.WriteLine(ForthTues);
        }
    }

上面的代码将给出输出

6/24/2019
7/22/2019
8/26/2019

但是如果我将日期更改为以下日期,

var StartDate = DateTime.Parse("06/27/2019");
var EndDate = DateTime.Parse("09/28/2019");

我得到的正确输出是

6/24/2019
7/22/2019
8/26/2019
9/23/2019

1 个答案:

答案 0 :(得分:1)

将您的代码转换为非区域特定的内容,并进行一些调整,您似乎想要的内容如下:-

         var StartDate = new DateTime(2019,  6, 28);
         var EndDate = new DateTime(2019, 9, 27);

         var startMonth = StartDate.AddDays(1 - StartDate.Day);
         var endMonth = EndDate.AddDays(1 - EndDate.Day);

         for (var i = startMonth; i <= endMonth; i = i.AddMonths(1))
         {
            int difference = (int)DayOfWeek.Monday - (int)i.DayOfWeek;
            int addDays = difference >= 0 ? 21 : 28;
            int days = difference + addDays;
            var fourthTuesday = i.AddDays(days);
            if (fourthTuesday <= EndDate )
               Console.WriteLine(fourthTuesday);
         }