你如何遍历一年中的每一天?

如果开始date为2009年1月1日,并且结束date为2009年12月31日,那么我怎样才能遍历每个date并使用c#获取date时间值?

谢谢!

我会用一个看起来像这样的循环

for(DateTime date = begin; date <= end; date = date.AddDays(1)) { } 

相应地设置开始和结束

另一个实现迭代器devise模式的选项:

这可能听起来没有必要,但是我依赖于如何使用这个function,你也可以实现Iterator的devise模式 。

想想这个。 假设一切正常,你可以复制/粘贴“for”句子。 突然间,作为要求的一部分,你必须重复所有的日子,但跳过其中一些(如在日历中,跳过holydays,周末,自定义等)

你将不得不创build一个新的“剪切”,并使用日历。 然后search并replace所有的。

在OOP中,这可以使用Iterator模式来实现。

从Wikpedia:

在面向对象编程中,迭代器模式是一种devise模式,其中使用迭代器顺序地访问聚合对象的元素, 而不暴露其基础表示 迭代器对象封装了迭代如何发生的内部结构。

所以这个想法是使用这样的结构:

  DateTime fromDate = DateTime.Parse("1/1/2009"); DateTime toDate = DateTime.Parse("12/31/2009"); // Create an instance of the collection class DateTimeEnumerator dateTimeRange = new DateTimeEnumerator( fromDate, toDate ); // Iterate with foreach foreach (DateTime day in dateTimeRange ) { System.Console.Write(day + " "); } 

然后,如果需要,你可以创build子类来实现不同的algorithm,一个使用AddDay(1),其他使用AddDay(7)或其他简单的使用日历。 等等

这个想法是降低对象之间的耦合。

再说一遍,对于大多数情况来说,这将是矫枉过正的,但是如果迭代构成系统的相关部分(比方说,你正在为企业创build某种通知,并且应该遵守不同的全球化

当然的基本实现将使用for。

 public class DateTimeEnumerator : System.Collections.IEnumerable { private DateTime begin; private DateTime end; public DateTimeEnumerator ( DateTime begin , DateTime end ) { // probably create a defensive copy here... this.begin = begin; this.end = end; } public System.Collections.IEnumerator GetEnumerator() { for(DateTime date = begin; date < end; date = date.AddDays(1)) { yield return date; } } } 

只是一个想法:)

 DateTime dateTime = new DateTime(2009, 1, 1); while(dateTime.Year < 2010) { dateTime = dateTime.AddDays(1); } 

我会使用MiscUtil及其扩展方法:

 foreach(DateTime date in 1.January(2009) .To(31.December(2009)) .Step(1.Days()) { Console.WriteLine(date); } 

设置两个variables:

 DateTime lowValue = DateTime.Parse("1/1/2009"); DateTime highValue = DateTime.Parse("12/31/2009"); 

然后,增加一天到低价值,直到它等于高价值:

 while (lowValue <= highValue) { //Do stuff here lowValue = lowValue.AddDays(1); } 

或类似的东西。

另一种更可重用的方法是在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上访问。

int day; for (int i = 1; i<365;i++) { day++; }

对不起,无法抗拒。

 DateTime current = DateTime.Parse("1/1/2009"); DateTime nextYear = current.AddYears(1); do { Console.WriteLine(current); current = current.AddDays(1); } while (current < nextYear) ;