简体   繁体   English

获取从StartDate到EndDate的日期列表

[英]Get list of dates from StartDate to EndDate

How can i get list of dates between start and end dates using linq or lambda expression. 如何使用linq或lambda表达式获取开始日期和结束日期之间的日期列表。

DateTime StartDate = DateTime.Now;
DateTime EndDate = DateTime.Now.AddMonths(13);
List<DateTime> ListofDates = //Contains list of all dates only between start and end date.
Enumerable.Range(0, (EndDate - StartDate).Days).Select(i => StartDate.AddDays(i))

First of all, when you want Dates and not Datetimes you better use DateTime.Now.Date instead of just DateTime.Now 首先,当你想要Dates而不是Datetimes ,最好使用DateTime.Now.Date而不仅仅是DateTime.Now

I've edited SLaks code so you can get the list of dates you want. 我编辑了SLaks代码,因此您可以获得所需的日期列表。

DateTime StartDate = DateTime.Now.Date;
DateTime EndDate = DateTime.Now.Date.AddMonths(13);
IEnumerable<double> daysToAdd = Enumerable.Range(0,
                                                (EndDate - StartDate).Days + 1)
                                            .ToList().ConvertAll(d => (double)d);
IEnumerable<DateTime> ListOfDates = daysToAdd.Select(StartDate.AddDays).ToList();

Note that I've added +1 in the enumerable so you can have both the start and end date (you didn't specify it) 请注意,我在枚举中添加了+1 ,因此您可以同时拥有start日期和end日期(您没有指定它)

List<DateTime> ListofDates = Enumerable.Range(0, (EndDate - StartDate).Days)
                                       .Select(i => StartDate.AddDays(i))
                                       .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 获取两个给定日期之间所有周的 StartDate 和 EndDate 列表 - C# Get a List of StartDate and EndDate of all the Weeks Between two given dates 使用linq group by从具有DateTime属性的对象列表获取具有间隔StartDate,EndDate的列表 - Using linq group by to get from a list of objects with a DateTime property to a list with an interval StartDate, EndDate 如何在查询C#中检查开始日期和结束日期之间的多个日期 - how to check multiple dates between startdate and enddate in query c# 在C#列表的下一个列表项中基于StartDate设置EndDate - Setting EndDate based on StartDate in next list item in a C# List 根据开始日期和结束日期从MSSQL表中获取数据 - Getting data from mssql table based on startdate and enddate 如何从startDate和endDate日期时间对象中排除星期六和星期日 - how to exclude Saturday and Sunday from startDate and endDate datetime objects 日期验证 - StartDate,EndDate MVC - Date Validations - StartDate, EndDate MVC 如果日期相同,则带有startDate和endDate的Daterange不起作用 - Daterange with startDate and endDate not working if both date same 如何自动更新startDate和EndDate以便下次执行? - How to auto update startDate and EndDate for next execution? PayPal Webservice for TransactionSearch不遵守StartDate / EndDate - PayPal Webservice for TransactionSearch does not respect StartDate/EndDate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM