C# 如何遍历日期范围?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1847580/
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-06 21:22:09  来源:igfitidea点击:

How do I loop through a date range?

c#asp.netdatetimeloops

提问by onekidney

I'm not even sure how to do this without using some horrible for loop/counter type solution. Here's the problem:

我什至不确定如何在不使用一些可怕的 for 循环/计数器类型解决方案的情况下做到这一点。这是问题所在:

I'm given two dates, a start date and an end date and on a specified interval I need to take some action. For example: for every date between 3/10/2009 on every third day until 3/26/2009 I need to create an entry in a List. So my inputs would be:

我有两个日期,一个开始日期和一个结束日期,并且在指定的时间间隔内我需要采取一些行动。例如:对于从 2009 年 3 月 10 日到 2009 年 3 月 26 日之间的每三天,我需要在列表中创建一个条目。所以我的输入是:

DateTime StartDate = "3/10/2009";
DateTime EndDate = "3/26/2009";
int DayInterval = 3;

and my output would be a list that has the following dates:

我的输出将是一个具有以下日期的列表:

3/13/2009 3/16/2009 3/19/2009 3/22/2009 3/25/2009

3/13/2009 3/16/2009 3/19/2009 3/22/2009 3/25/2009

So how the heck would I do something like this? I thought about using a for loop that would iterate between every day in the range with a separate counter like so:

那么我怎么会做这样的事情呢?我想过使用一个 for 循环,它会在范围内的每一天之间使用一个单独的计数器进行迭代,如下所示:

int count = 0;

for(int i = 0; i < n; i++)
{
     count++;
     if(count >= DayInterval)
     {
          //take action
          count = 0;
     }

}

But it seems like there could be a better way?

但似乎有更好的方法?

采纳答案by mqp

Well, you'll need to loop over them one way or the other. I prefer defining a method like this:

好吧,您需要以一种或另一种方式遍历它们。我更喜欢定义这样的方法:

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
    for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
        yield return day;
}

Then you can use it like this:

然后你可以像这样使用它:

foreach (DateTime day in EachDay(StartDate, EndDate))
    // print it or whatever

In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3)in the loop instead of AddDays(1).

通过这种方式,您可以每隔一天、每三天、仅在工作日等等。例如,要从“开始”日期开始每三天返回一次,您可以只AddDays(3)在循环中调用而不是AddDays(1).

回答by TLiebe

You can use the DateTime.AddDays()function to add your DayIntervalto the StartDateand check to make sure it is less than the EndDate.

您可以使用该 DateTime.AddDays()函数将您DayInterval的添加到StartDate并检查以确保它小于EndDate

回答by Adriaan Stander

For your example you can try

对于您的示例,您可以尝试

DateTime StartDate = new DateTime(2009, 3, 10);
DateTime EndDate = new DateTime(2009, 3, 26);
int DayInterval = 3;

List<DateTime> dateList = new List<DateTime>();
while (StartDate.AddDays(DayInterval) <= EndDate)
{
   StartDate = StartDate.AddDays(DayInterval);
   dateList.Add(StartDate);
}

回答by Jon Skeet

I have a Rangeclass in MiscUtilwhich you could find useful. Combined with the various extension methods, you could do:

RangeMiscUtil 中有一个类,您会发现它很有用。结合各种扩展方法,您可以:

foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
                                   .Step(DayInterval.Days())
{
    // Do something with the date
}

(You may or may not want to exclude the end - I just thought I'd provide it as an example.)

(您可能想也可能不想排除结尾 - 我只是想我会提供它作为一个例子。)

This is basically a ready-rolled (and more general-purpose) form of mquander's solution.

这基本上是 mquander 解决方案的现成(和更通用)形式。

回答by devnull

DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;

while ((startDate = startDate.AddDays(interval)) <= stopDate)
{
    // do your thing
}

回答by gilbertc

DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;

for (DateTime dateTime=startDate;
     dateTime < stopDate; 
     dateTime += TimeSpan.FromDays(interval))
{

}

回答by REDace0

You might consider writing an iterator instead, which allows you to use normal 'for' loop syntax like '++'. I searched and found a similar question answeredhere on StackOverflow which gives pointers on making DateTime iterable.

您可能会考虑编写一个迭代器,它允许您使用像 '++' 这样的普通 'for' 循环语法。我搜索,发现了一个类似的问题回答这里StackOverflow上这给制作日期时间迭代指针。

回答by Jacob Sobus

Code from @mquander and @Yogurt The Wise used in extensions:

来自@mquander 和@Yogurt The Wise 的代码在扩展中使用:

public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
    for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
        yield return day;
}

public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
    for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1))
        yield return month;
}

public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
    return EachDay(dateFrom, dateTo);
}

public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
    return EachMonth(dateFrom, dateTo);
}

回答by Rejwanul Reja

According to the problem you can try this...

根据问题你可以试试这个...

// looping between date range    
while (startDate <= endDate)
{
    //here will be your code block...

    startDate = startDate.AddDays(1);
}

thanks......

谢谢......

回答by Robert Peter Bronstein

you have to be careful here not to miss the dates when in the loop a better solution would be.

你必须小心不要错过循环中的日期,一个更好的解决方案是。

this gives you the first date of startdate and use it in the loop before incrementing it and it will process all the dates including the last date of enddate hence <= enddate.

这为您提供 startdate 的第一个日期,并在增加它之前在循环中使用它,它将处理所有日期,包括 enddate 的最后日期,因此 <= enddate。

so the above answer is the correct one.

所以上面的答案是正确的。

while (startdate <= enddate)
{
    // do something with the startdate
    startdate = startdate.adddays(interval);
}