我有一个DateTimeStartDate和EndDate.
无论何时,我怎样才能在这两者之间每天进行迭代?
示例:StartDate是2010年7月20日下午5:10:32,EndDate是7/29/2010 1:59:12 AM.
我希望能够跨越7/20,7/21,7/22 .. 7/29进行迭代.
Yur*_*ich 125
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
...
}
Run Code Online (Sandbox Code Playgroud)
.Date是为了确保你有最后一天,就像在例子中一样.
hea*_*jnr 14
可能更可重用的替代方法是在DateTime上编写扩展方法并返回IEnumerable.
例如,您可以定义一个类:
public static class MyExtensions
{
public static IEnumerable EachDay(this DateTime start, DateTime end)
{
// Remove time info from start date (we only care about day).
DateTime currentDay = new DateTime(start.Year, start.Month, start.Day);
while (currentDay <= end)
{
yield return currentDay;
currentDay = currentDay.AddDays(1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在在调用代码中,您可以执行以下操作:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(20);
foreach (var day in start.EachDay(end))
{
...
}
Run Code Online (Sandbox Code Playgroud)
这种方法的另一个优点是它使添加EveryWeek,EachMonth等变得微不足道.然后,这些都可以在DateTime上访问.