How to loop between two dates

后端 未结 5 1355
面向向阳花
面向向阳花 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: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]

提交回复
热议问题