2010-07-29 42 views
44

我有一個DateTime StartDate和EndDate。在StartDate和EndDate之間每一天迭代

我怎樣才能不管次數在這兩者之間的每一天迭代?

例如:StartDate是7/20/2010 5:10:32 PM和EndDate是7/29/2010 1:59:12 AM。

我希望能夠遍歷7/20,7/21,7/22 .. 7/29。

+0

看看這裏: http://stackoverflow.com/questions/533767/how-do-you-iterate-through-every-day-of-the-year – 2010-07-29 05:50:04

回答

112
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1)) 
{ 
    ... 
} 

.Date是爲了確保你有最後一天,就像在這個例子中。

+0

我想你想'date.Date <= EndDate.Date',讓你得到最後一天。 – 2010-07-29 05:51:04

+2

這樣進入一個無限循環中,AddDays方法不更改日期,但返回一個新的DateTime實例。 使用日期= date.AddDays(1)來代替。 – corvuscorax 2010-07-29 05:55:30

+0

@Dean:謝謝,看到你的評論後改變。 – 2010-07-29 05:56:40

0
DateTime date = DateTime.Now; 
DateTime endDate = date.AddDays(10); 

while (date < endDate) 
{ 
    Console.WriteLine(date); 
    date = date.AddDays(1); 
} 
3

你必須小心結束日期。例如,在

例如:StartDate是7/20/2010 5:10:32 PM和EndDate是7/29/2010 1:59:12 AM。
我希望能夠遍歷7/20,7/21,7/22 .. 7/29。

date < endDate將不包括7/29有史以來。當你添加1天到7/28 5:10 PM時,它會變成7/29 5:10 PM,高於7/29 2 AM。

如果這不是你想要的話,我會說你做

for (DateTime date = start.Date; date <= end.Date; date += TimeSpan.FromDays(1)) 
{ 
    Console.WriteLine(date.ToString()); 
} 

或諸如此類的話。

11

另一種更可重用的方法是在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); 
     } 
    } 
} 

現在,您可以執行以下操作:

例如,你可以定義一個類

DateTime start = DateTime.Now; 
DateTime end = start.AddDays(20); 
foreach (var day in start.EachDay(end)) 
{ 
    ... 
} 

這種方法的另一個好處是,它可以輕鬆地將添加EachWeek,EachMonth等等。然後這些都可以在DateTime上訪問。

+1

您可以使用DateTime.Date從日期中刪除時間信息:https://msdn.microsoft.com/en-us/library/system.datetime.date(v=vs.110).aspx – Oswin 2016-08-18 13:58:29

+1

爲什麼你不做類型安全嗎? IEnumerable ? – duedl0r 2018-01-12 00:00:40

0

@Yuriy Faktorovich的循環,@healsjnr和@mho都會拋出一個System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime 異常,如果EndDate == DateTime.MaxValue。 爲了防止這種情況,在環

for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1)) 
{ 
    ... 
    if (date.Date == DateTime.MaxValue.Date) 
    { 
     break; 
    } 
} 

的末尾添加額外的檢查(我會公佈這爲@Yuriy Faktorovich的答案評論,但我缺乏信譽)

相關問題