Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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 should return me a list of date (List), and it must contain 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010, and 05.01.2010.

I wrote a function like this. It works fine, if my dates are in a month. It won't work if my dates are like 01.01.2010 - 05.02.2010. Because the month changed, and my function can't handle it. Is there a function in C# that returns all dates between two dates? Or how can I handle month change?

public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)     {         List<DateTime> allDates = new List<DateTime>();          int starting = startingDate.Day;         int ending = endingDate.Day;          for (int i = starting; i <= ending; i++)         {             allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i));         } 

Question solved, see Tim Robinson's simple answer to use.

like image 773
Serkan Hekimoglu Avatar asked Jul 12 '10 11:07

Serkan Hekimoglu


People also ask

How do I find the date between two dates?

We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.

How do I get the difference between two times in C#?

DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 8, 17, 11, 14, 25); Now, get the difference between two dates. TimeSpan ts = date2 - date1; Get the result i.e. the difference in hours.


2 Answers

You can use DateTime objects directly in the loop, in place of your int. DateTime.AddDays handles month ends correctly.

for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))     allDates.Add(date); 
like image 192
Tim Robinson Avatar answered Sep 20 '22 18:09

Tim Robinson


How about something like this?

public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate) {     return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)                      .Select(d => fromDate.AddDays(d)); } 

Edit: Tested now. :)

like image 23
Matt Hamilton Avatar answered Sep 16 '22 18:09

Matt Hamilton