2009-07-29 46 views
16

我有一個將選定日期作爲字符串傳遞給方法的日曆。在此方法中,我希望生成從所選開始日期開始到選定結束日期的所有日期的列表,顯然包括所有日期之間的所有日期,無論所選開始日期和結束日期之間有多少天。如何在兩個日期之間循環

下面我有方法的開始,它接受日期字符串並將它們轉換爲DateTime變量,以便我可以使用DateTime計算函數。但是,我似乎無法計算出如何計算開始和結束日期之間的所有日期? 很明顯,第一階段是從結束日期中減去開始日期,但我無法計算其餘的步驟。

幫助大大加分,

親切的問候。

public void DTCalculations() 
{ 
List<string> calculatedDates = new List<string>(); 
string startDate = "2009-07-27"; 
string endDate = "2009-07-29"; 

//Convert to DateTime variables 
DateTime start = DateTime.Parse(startDate); 
DateTime end = DateTime.Parse(endDate); 

//Calculate difference between start and end date. 
TimeSpan difference = end.Subtract(start); 

//Generate list of dates beginning at start date and ending at end date. 
//ToDo: 
} 
+0

在生成的值(日期,小時,分鐘)之間制定了一個步驟 – 2009-07-29 09:51:01

回答

33
static IEnumerable<DateTime> AllDatesBetween(DateTime start, DateTime end) 
{ 
    for(var day = start.Date; day <= end; day = day.AddDays(1)) 
     yield return day; 
} 

編輯:添加代碼來解決您的具體例子,證明使用:

var calculatedDates = 
    new List<string> 
    (
     AllDatesBetween 
     (
      DateTime.Parse("2009-07-27"), 
      DateTime.Parse("2009-07-29") 
     ).Select(d => d.ToString("yyyy-MM-dd")) 
    ); 
2

做將採取的開始日期,1天添加到它的最簡單的事情(使用AddDays),直到到達結束日期。事情是這樣的:

DateTime calcDate = start.Date; 
while (calcDate <= end) 
{ 
    calcDate = calcDate.AddDays(1); 
    calculatedDates.Add(calcDate.ToString()); 
} 

很明顯,你會調整,而條件和AddDays的位置呼叫根據,如果你想以包括收集或沒有開始和結束日期。

[編輯:順便說一下,你應該考慮使用的TryParse(),而不是解析()的情況下,在字符串中傳遞沒有轉換日期好聽]

+0

確保結束日期也大於開始日期,因此您不會陷入無限循環。 :) – 2009-07-29 09:51:02

+1

格雷格,你不應該與==檢查,但與<= – 2009-07-29 09:52:32

1
for(DateTime i = start; i <= end; i = i.AddDays(1)) 
{ 
    Console.WriteLine(i.ToShortDateString()); 
} 
+0

你有for循環使用'i'作爲變量的要點。非常感謝你。 – 2017-12-22 16:14:48

4

你只需要從迭代開始到結束,您可以循環在做這個

DateTime start = DateTime.Parse(startDate); 
DateTime end = DateTime.Parse(endDate); 

for(DateTime counter = start; counter <= end; counter = counter.AddDays(1)) 
{ 
    calculatedDates.Add(counter); 
} 
0

的另一種方法

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上訪問。

相關問題