开发者

Get Dates between Ranges, c#

I've two dates

  1. 21/01/2011 [From Date]
  2. 25/01/2011 [To Date]

How can I get all the dates be开发者_开发问答tween these ranges using c#

The answer should be

21/01/2011

22/01/2011

23/01/2011

24/01/2011

25/01/2011


var allDates = Enumerable.Range(0, int.MaxValue)
                         .Select(x => fromDate.Date.AddDays(x))
                         .TakeWhile(x => x <= toDate.Date);


I'm sure this can help you: http://geekswithblogs.net/thibbard/archive/2007/03/01/CSharpCodeToGetGenericListOfDatesBetweenStartingAndEndingDate.aspx


var dateArr = new List<DateTime>();

for (var date = startDate; date <= endDate; date = date.AddDays(1)) {
   dateArr.Add(date);
}

Now dateArr contains your required dates.


public System.Collections.Generic.IEnumerable<DateTime> GetDatesBetween(
    DateTime start,
    DateTime end
    )
{
    DateTime current = start;
    while (current <= end) 
    {
        yield return current.Date;
        current = current.AddDays(1);
    }
}

should do the job

[edit] Added the .Date to "round" the date to midnigth


How about:

        var startDT = new DateTime(2011, 01, 21);
        var endDT = new DateTime(2011, 01, 25);
        var workDT = startDT;
        do
        {
            Console.WriteLine(workDT.ToString("dd/MM/yyyy"));
            workDT = workDT.AddDays(1);
        } while (workDT <= endDT);
        Console.ReadLine();


I dont know if we have anything to do this inbuilt in Framework but you can try this:

DateTime dt1 = new DateTime(2011,01,21);
DateTime dt2 = new DateTime(2011,01,25);
List<DateTime> datetimerange = new List<DateTime>();
while(DateTime.Compare(dt1,dt2) <= 0)
{
        datetimerange.Add(dt1);
        dt1 = dt1.AddDays(1);

}


if (toDate < fromDate)
  return;

var days = (new DateTime[(toDate - fromDate).Days + 1).
             Select((x, i) => fromDate.AddDays(i));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜