Getting all DateTimes between two 'DateTime's in C#

前端 未结 8 620
清酒与你
清酒与你 2020-12-12 20:14

I have two DateTimes, and I want to get all DateTimes between these Dates. Such as, if my Dates are like 01.01.2010 - 05.01.2010, my function shoul

相关标签:
8条回答
  • 2020-12-12 20:59
    public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
    {
        if (endingDate < startingDate)
        {
            throw new ArgumentException("endingDate should be after startingDate");
        }
        var ts = endingDate - startingDate;
        for (int i = 0; i < ts.TotalDays; i++)
        {
            yield return startingDate.AddDays(i);
        }
    }
    
    0 讨论(0)
  • 2020-12-12 21:02

    You were so close... just don't use the day, use the whole date.

    static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
    {
        List<DateTime> allDates = new List<DateTime>();
    
    
        for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
        {
            allDates.Add(i);
        }
        return allDates.AsReadOnly();
    }
    
    0 讨论(0)
提交回复
热议问题