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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/533767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:07:05  来源:igfitidea点击:

How do you iterate through every day of the year?

c#datetime

提问by Chris Conway

Given a start date of 1/1/2009 and an end date of 12/31/2009, how can I iterate through each date and retrieve a DateTime value using c#?

给定开始日期 1/1/2009 和结束日期 12/31/2009,如何使用 c# 遍历每个日期并检索 DateTime 值?

Thanks!

谢谢!

采纳答案by Samantha Branham

I would use a loop that looks like this

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

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

Set begin and end accordingly

相应地设置开始和结束

回答by kemiller2002

DateTime dateTime = new DateTime(2009, 1, 1);    

while(dateTime.Year < 2010)
    {

      dateTime = dateTime.AddDays(1);
    }

回答by jgallant

Set two variables:

设置两个变量:

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

Then, add a day to the low value until it is equal to highvalue:

然后,将一天添加到低值,直到它等于高值:

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

Or something like that.

或类似的东西。

回答by DMCS

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

回答by Robert S.

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

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

Sorry, couldn't resist.

对不起,忍不住了。

回答by Jon Skeet

I'd use MiscUtiland its extension methods:

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

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

回答by OscarRyz

Another option implementing the Iterator design pattern:

实现迭代器设计模式的另一种选择:

This may sound unnecessary, but I depending on how to you use this functionality, you may also implement the Iterator design pattern.

这听起来可能没有必要,但根据您如何使用此功能,您也可以实现Iterator 设计模式

Think on this. Suppose that everything works just fine, and you copy/paste all over the place the "for" sentence. And suddenly as part of the requirements, you have to iterate all the days but skip some of them ( like in calendar, skip holydays, weekends, custom etc. )

想想这个。假设一切正常,并且您将“for”语句复制/粘贴到各处。突然作为要求的一部分,你必须迭代所有的日子,但跳过其中的一些(比如在日历中,跳过圣日、周末、自定义等)

You would have to create a new "snipped" and use Calendar instead. Then search and replace all your for's.

您将不得不创建一个新的“剪辑”并改用日历。然后搜索并替换所有的 for 。

In OOP, this could be achieved using the Iterator pattern.

在 OOP 中,这可以使用迭代器模式来实现。

From Wikpedia:

来自维基百科:

In object-oriented programming, the Iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.

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

So the idea is to use a construct like this:

所以我们的想法是使用这样的构造:

        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 + " ");
        }

And then if needed you could create subclasses to implement different algorithms, one that uses AddDay(1), other that uses AddDay( 7 ) or other that simple uses Calendar instead. Etc. etc.

然后,如果需要,您可以创建子类来实现不同的算法,一个使用 AddDay(1),另一个使用 AddDay(7) 或其他简单的使用 Calendar 代替。等等等等。

The idea is to lower the coupling between objects.

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

Again, this would be overkill for most of the cases, but if the iteration forms a relevantpart of a system ( let's say , you are creating some kind of whatever notification, for an enterprise, and should adhere to different globalizations

同样,在大多数情况下,这将是矫枉过正,但如果迭代形成系统的相关部分(比方说,您正在为企业创建某种任何通知,并且应该坚持不同的全球化

The basic implementation of course would use the for.

基本的实现当然会使用 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;
        }
    }
}

Just an idea :)

只是一个想法:)

回答by healsjnr

An alternative method that might be more reusable is to write an extension method on DateTime and return an IEnumerable.

另一种可能更可重用的方法是在 DateTime 上编写扩展方法并返回 IEnumerable。

For example, you can define a class:

例如,您可以定义一个类:

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);
        }
    }
}

Now in the calling code you can do the following:

现在在调用代码中,您可以执行以下操作:

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

Another advantage to this approach is that it makes it trivial to add EachWeek, EachMonth etc. These will then all be accessible on DateTime.

这种方法的另一个优点是添加 EachWeek、EachMonth 等变得微不足道。然后这些都可以在 DateTime 上访问。