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.
LINQ:
Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.ToArray();
For loop:
var dates = new List<DateTime>();
for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
dates.Add(dt);
}
EDIT: As for padding values with defaults in a time-series, you could enumerate all the dates in the full date-range, and pick the value for a date directly from the series if it exists, or the default otherwise. For example:
var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date)
? timeSeries[date] : defaultValue);
public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
if (endDate < startDate)
throw new ArgumentException("endDate must be greater than or equal to startDate");
while (startDate <= endDate)
{
yield return startDate;
startDate = startDate.AddDays(1);
}
}
I know this is an old post but try using an extension method:
public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
}
and use it like this
var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));
Feel free to choose your own dates, you don't have to restrict yourself to January 2000.
Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With