1 год спустя, может это кому-нибудь помочь,
Эта версия включает в себя предикат , чтобы быть более гибким.
Использование
var today = DateTime.UtcNow;
var birthday = new DateTime(2018, 01, 01);
Ежедневно до моего дня рождения
var toBirthday = today.RangeTo(birthday);
Ежемесячно до моего дня рождения, Шаг 2 месяца
var toBirthday = today.RangeTo(birthday, x => x.AddMonths(2));
Ежегодно до моего дня рождения
var toBirthday = today.RangeTo(birthday, x => x.AddYears(1));
Используйте RangeFrom
вместо
// same result
var fromToday = birthday.RangeFrom(today);
var toBirthday = today.RangeTo(birthday);
Осуществление
public static class DateTimeExtensions
{
public static IEnumerable<DateTime> RangeTo(this DateTime from, DateTime to, Func<DateTime, DateTime> step = null)
{
if (step == null)
{
step = x => x.AddDays(1);
}
while (from < to)
{
yield return from;
from = step(from);
}
}
public static IEnumerable<DateTime> RangeFrom(this DateTime to, DateTime from, Func<DateTime, DateTime> step = null)
{
return from.RangeTo(to, step);
}
}
Дополнительно
Вы можете выдать исключение, если fromDate > toDate
, но я предпочитаю возвращать пустой диапазон вместо []