How to loop between two dates

后端 未结 5 1350
面向向阳花
面向向阳花 2021-02-04 02:12

I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and

相关标签:
5条回答
  • 2021-02-04 02:29

    An alternative method

    public static class MyExtensions
    {
        public static IEnumerable EachDay(this DateTime start, DateTime end)
        {
            // Remove time info from start date (we only care about day). 
            DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
            while (currentDay <= end)
            {
                yield return currentDay;
                currentDay = currentDay.AddDays(1);
            }
        }
    }
    

    Now in the calling code you can do the following:

    DateTime start = DateTime.Now;
    DateTime end = start.AddDays(20);
    foreach (var day in start.EachDay(end))
    {
        ...
    }
    

    Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.

    0 讨论(0)
  • 2021-02-04 02:33

    The easiest thing to do would be take the start date, and add 1 day to it (using AddDays) until you reach the end date. Something like this:

    DateTime calcDate = start.Date;
    while (calcDate <= end)
    {
        calcDate = calcDate.AddDays(1);
        calculatedDates.Add(calcDate.ToString());
    }
    

    Obviously, you would adjust the while conditional and the position of the AddDays call depending on if you wanted to include the start and end dates in the collection or not.

    [Edit: By the way, you should consider using TryParse() instead of Parse() in case the passed in strings don't convert to dates nicely]

    0 讨论(0)
  • 2021-02-04 02:41
    for( DateTime i = start; i <= end; i = i.AddDays( 1 ) )
    {
        Console.WriteLine(i.ToShortDateString());
    }
    
    0 讨论(0)
  • 2021-02-04 02:47

    You just need to iterate from start to end, you can do this in a for loop

    DateTime start = DateTime.Parse(startDate);
    DateTime end = DateTime.Parse(endDate);
    
    for(DateTime counter = start; counter <= end; counter = counter.AddDays(1))
    {
        calculatedDates.Add(counter);
    }
    
    0 讨论(0)
  • 2021-02-04 02:49
    static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end)
    {
        for(var day = start.Date; day <= end; day = day.AddDays(1))
            yield return day;
    }
    

    Edit: Added code to solve your particular example and to demonstrate usage:

    var calculatedDates = 
        new List<string>
        (
            AllDatesBetween
            (
                DateTime.Parse("2009-07-27"),
                DateTime.Parse("2009-07-29")
            ).Select(d => d.ToString("yyyy-MM-dd"))
        );
    
    0 讨论(0)
提交回复
热议问题