Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a start and end date... find all dates within range in C#

Given DateTime start = startsomething and DateTime end = endSomething

Is there a standard way to return all Dates within start and end such that the return is a list of Dates like ...

'1/1/2012 12:00 AM'
'1/2/2012 12:00 AM'
like image 384
crazyDiamond Avatar asked Oct 17 '25 19:10

crazyDiamond


2 Answers

You can create a method like this:

public static IEnumerable<DateTime> Range(DateTime start, DateTime end) {
  for (var dt = start; dt <= end; dt = dt.AddDays(1)) {
    yield return dt;
  }
}
like image 81
Jordão Avatar answered Oct 20 '25 08:10

Jordão


The Linq way:

DateTime start = new DateTime(2012, 1, 1);
DateTime end = new DateTime(2012, 6, 1);

var list = Enumerable.Range(0, (end - start).Days + 1).Select(i => start.AddDays(i));
like image 41
D Stanley Avatar answered Oct 20 '25 08:10

D Stanley