Csharp/C#教程:如何在两个日期之间循环分享


如何在两个日期之间循环

我有一个日历,它将选定日期作为字符串传递给方法。 在此方法中,我想生成一个列表,其中列出了从所选开始日期开始到所选结束日期的所有日期,显然包括所有日期,无论在所选开始日期和结束日期之间有多少天。

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

非常感谢,

亲切的问候。

public void DTCalculations() { List calculatedDates = new List(); 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 AllDatesBetween(DateTime start, DateTime end) { for(var day = start.Date; day <= end; day = day.AddDays(1)) yield return day; } 

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

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

您只需要从头到尾进行迭代,就可以在for循环中执行此操作

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

最简单的方法是采取开始日期,并添加1天(使用AddDays),直到您到达结束日期。 像这样的东西:

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

显然,您可以调整while条件和AddDays调用的位置,具体取决于您是否要在集合中包含开始日期和结束日期。

[编辑:顺便说一句,你应该考虑使用TryParse()而不是Parse(),以防传入的字符串不能很好地转换为日期]

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

另一种方法

 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)) { ... } 

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

上述就是C#学习教程:如何在两个日期之间循环分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1006682.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐