I have a function to decrement a date by one day each time is called.
private IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = thru.Date; day.Date >= from.Date; day = day.Subtract(TimeSpan.FromDays(1)))//day.AddDays(-1))
{
yield return day;
}
}
Seems to work fine until i arrive to the previous month. If someone have a solution ?
CodePudding user response:
I would be using something like this
private IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
var days=(thru.Date - from.Date).Days;
if (days <= 0) yield return DateTime.MinValue;
else for (var day = days; day >= 0; day-=1)
yield return from.Date.AddDays(day);
}
test
var thru =new DateTime(day: 01,month:12, year:2021);
var from= thru.AddDays(-10);
EachDay(from,thru).Dump();
result
2021-12-01
2021-11-30
2021-11-29
2021-11-28
2021-11-27
2021-11-26
2021-11-25
2021-11-24
2021-11-23
2021-11-22
2021-11-21
CodePudding user response:
To some extent you're reinventing a wheel here. You can use Enumerable.Range to do your dates:
var f = DateTime.Now;
var t = DateTime.Now.AddDays(-45);
var d = Enumerable.Range(0, (int)((f-t).TotalDays)).Select(x => f.AddDays(-x));
The dates in d
have no problem crossing a month boundary