easy way to loop over months and years from a given date

前端 未结 6 1431
星月不相逢
星月不相逢 2020-12-20 11:53

I have been trying to write this loop and it just keeps getting more complicated. Basically I want to take a given date and loop through every month until I reach the curren

相关标签:
6条回答
  • 2020-12-20 12:04
    DateTime endDate = DateTime.Today;
    for (DateTime dt = startDate; dt <= endDate; dt = dt.AddMonths(1))
    {
        Console.WriteLine("{0:M/yyyy}", dt);
    }
    

    But if you prefer while loops, then vote for Dan-o. I did. :)

    0 讨论(0)
  • 2020-12-20 12:09

    This will loop over the months and the day of the month will not be a problem.

    var date = startDate;
    var endDate = DateTime.Now;
    
    while(date.Year < endDate.Year || (date.Year == endDate.Year && date.Month <= endDate.Month))
    {
        Console.WriteLine($"{date.Month}/{date.Year}");
        date = date.AddMonths(1);
    }
    
    0 讨论(0)
  • 2020-12-20 12:14

    Sam's answer is nice but ultimately incorrect (if your start day is 20 and your end day is 10, it won't include the last month). Here's a version that works:

        public void GetMonths(DateTime startTime, DateTime endTime)
        {
            var dateCounter = new DateTime(startTime.Year, startTime.Month, 1);
            var endDateTarget = new DateTime(endTime.Year, endTime.Month, 1);
    
            while (dateCounter <= endDateTarget)
            {
                Console.WriteLine($"The year and month is: {dateCounter.Year}, {dateCounter.Month}");
                dateCounter = dateCounter.AddMonths(1);
            }
        }
    
    0 讨论(0)
  • 2020-12-20 12:16
    Date target = new Date(2011, 4, 1);
    while (target < Date.Today) {
      // do something with target.Month and target.Year
      target = target.AddMonths(1);
    }
    
    0 讨论(0)
  • 2020-12-20 12:16
    while (startDate <= DateTime.Now)
                {
                    //here you will get every new month in  year
                    Console.WriteLine(startDate.Month);
                    //Add Month
                    startDate=startDate.AddMonths(1);
                }
    
    0 讨论(0)
  • 2020-12-20 12:18

    Generate a range (as IEnumerable`DateTime) of first days of a month in between of a given dates:

    from range in new[] {
        new {
            start = new DateTime(2017, 6, 23),
            end = new DateTime(2018, 09, 11)
        }
    }
    select (
        from y in Enumerable.Range(
            range.start.Year, range.end.Year - 
            range.start.Year + 1
        )
        let ms = y == range.start.Year ? range.start.Month : 1
        let me = y == range.end.Year ? range.end.Month : 12
        select 
            from m in Enumerable.Range(ms, me - ms + 1)
            select new DateTime(y, m, 1)
    ).SelectMany(y => y)
    
    0 讨论(0)
提交回复
热议问题