如何在两个日期之间循环 [英] How to loop between two dates

查看:118
本文介绍了如何在两个日期之间循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日历,通过选择的日期作为字符串进入方法。在此方法中,我想生成从所选开始日期开始并以所选结束日期结尾的所有日期的列表,显然包括所有日期在中间,而不管所选的开始和结束日期之间有多少天。



下面我有一个方法的开始,它接受日期字符串并将它们转换为DateTime变量,以便我可以使用DateTime计算函数。然而,我似乎无法计算出如何计算开始和结束日期之间的所有日期?
显然,第一个阶段是从结束日期减去开始日期,但是我无法计算剩余的步骤。



p>

kind $。

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

//转换为DateTime变量
DateTime start = DateTime.Parse(startDate);
DateTime end = DateTime.Parse(endDate);

//计算开始和结束日期之间的差异。
TimeSpan difference = end.Subtract(start);

//生成从开始日期开始到结束日期的日期列表。
// ToDo:
}


解决方案

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

编辑:添加代码来解决您的特定示例并演示用法: p>

  var calculatedDates = 
new List< string>

AllDatesBetween

DateTime.Parse(2009-07-27),
DateTime.Parse(2009-07-29)
)。选择(d => d.ToString(yyyy-MM-dd))
);


I have a calendar which passes selected dates as strings into a method. Inside this method, I want to generate a list of all the dates starting from the selected start date and ending with the selected end date, obviously including all of the dates inbetween, regardless of how many days are inbetween the selected start and end dates.

Below I have the beginning of the method which takes the date strings and converts them into DateTime variables so that I can make use of the DateTime calculation functions. However, I cannot seem to work out how to calculate all of the dates inbetween the start and end date? Obviously the first stage is to subtract the start date from the end date, but I cannot calculate the rest of the steps.

Help appreciated greatly,

kind regards.

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:
}

解决方案

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

Edit: Added code to solve your particular example and to demonstrate usage:

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

这篇关于如何在两个日期之间循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆