如何在C#的日期范围内获得所有周末
我只是想知道是否有一个简单的方法或框架来使所有周末在C#的日期范围内?
是否可以使用LINQ?
任何线索?
谢谢!
如果您想要枚举所有日子,可以使用linq过滤到周末:
IEnumerable GetDaysBetween(DateTime start, DateTime end) { for (DateTime i = start; i < end; i = i.AddDays(1)) { yield return i; } } var weekends = GetDaysBetween(DateTime.Today, DateTime.Today.AddDays(365)) .Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);
我发现了怎么做。
https://www.dotnetjalps.com/2011/06/finding-saturdaysunday-between-date.html
namespace DatimeApplication { class Program { static void Main(string[] args) { DateTime startDate=new DateTime(2011,3,1); DateTime endDate = DateTime.Now; TimeSpan diff = endDate - startDate; int days = diff.Days; for (var i = 0; i <= days; i++) { var testDate = startDate.AddDays(i); switch (testDate.DayOfWeek) { case DayOfWeek.Saturday: case DayOfWeek.Sunday: Console.WriteLine(testDate.ToShortDateString()); break; } } Console.ReadLine(); } } }
这不是很难编码…这是一个有效的迭代器:
上述就是C#学习教程:如何在C#的日期范围内获得所有周末分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
public static IEnumerable GetWeekends(DateTime startDate, DateTime endDate) { startDate = startDate.Date; endDate = endDate.Date; if (endDate < startDate) yield break; var currentDate = startDate; // Advance to next Saturday switch (currentDate.DayOfWeek) { case DayOfWeek.Saturday: break; case DayOfWeek.Sunday: yield return currentDate; currentDate = currentDate.AddDays(6); break; default: currentDate = currentDate.AddDays(DayOfWeek.Saturday - currentDate.DayOfWeek); break; } while (currentDate <= endDate) { yield return currentDate; currentDate = currentDate.AddDays(1); if (currentDate <= endDate) yield return currentDate; currentDate = currentDate.AddDays(6); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1251016.html