Simple way to populate a List with a range of Datetime

做~自己de王妃 提交于 2021-02-05 05:37:04

问题


I trying to find a simple way to solve this.

I have a Initial Date, and a Final Date.

And I want to generate a List<Datetime> with each of the dates in a given period.


Example : Initial Date is "2013/12/01" and Final Date is "2013/12/05".

And I want to automatically populate a list with

"2013/12/01"
"2013/12/02"
"2013/12/03"
"2013/12/04"
"2013/12/05"

What would you suggest me?

Thanks


回答1:


var startDate = new DateTime(2013, 12, 1);
var endDate = new DateTime(2013, 12, 5);

var dates = Enumerable.Range(0, (int)(endDate - startDate).TotalDays + 1)
                      .Select(x => startDate.AddDays(x))
                      .ToList();



回答2:


for(var day = from.Date; day.Date <= end.Date; day = day.AddDays(1))
{
     list.Add(day);
}



回答3:


DateTime startDate = new DateTime(2013, 12, 1); // or any other start date
int numberOfDays = 5;
var dates  = Enumerable.Range(0, numberOfDays)
                       .Select(i => startDate.AddDays(i))
                       .ToList();



回答4:


You can use Linq like:

DateTime startDate = new DateTime(2013, 12, 1);
DateTime endDate = new DateTime(2013, 12, 5);
List<DateTime> dates =
                      Enumerable.Range(0, ((endDate - startDate).Days) + 1)
                      .Select(n => startDate.AddDays(n))
                      .ToList();

For output:

foreach (var item in dates)
{
    Console.WriteLine(item.ToShortDateString());
}

Output:

01/12/2013
02/12/2013
03/12/2013
04/12/2013
05/12/2013



回答5:


You can do something like this:

DECLARE @startdate datetime, @enddate datetime, @increment int
SET @startdate = '2013/12/01'
SET @enddate = '2013/12/05'
SET @increment = 0
WHILE DATEADD(dd, @increment, @startdate) <= @enddate
  BEGIN
    SELECT DATEADD(dd, @increment, @startdate)
    SET @increment = @increment + 1
  END

Inside the while loop you can put the values on a table or do whatever you wish instead of just printing them out.



来源:https://stackoverflow.com/questions/20382893/simple-way-to-populate-a-list-with-a-range-of-datetime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!