-1

Possible Duplicate:
Find missing dates for a given range
Create an array or List of all dates between two dates

From two dates of data type DateTime representing a date of start and a date of end.

I need return an array or List which contain all the dates in DateTime format.

Considering the faster code for performance reason. Could anyone please point me out in the right direction with sample source code?

Example

INPUT

startDate =  25/01/2013
endDate = 31/01/2013

RESULT

25/01/2013
26/01/2013
27/01/2013
28/01/2013
29/01/2013
30/01/2013
31/01/2013
Community
  • 1
  • 1
GibboK
  • 71,848
  • 143
  • 435
  • 658

4 Answers4

4

You can use Enumerable.Range:

var startDate = new DateTime(2013, 1, 25);
var endDate = new DateTime(2013, 1, 31);
int days = (endDate - startDate).Days + 1; // incl. endDate 

List<DateTime> range = Enumerable.Range(0, days)
    .Select(i => startDate.AddDays(i))
    .ToList();

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can create extension method:

public static IEnumerable<DateTime> GetDatesTo(this DateTime start, DateTime end)
{
    DateTime date = start;

    while(date <= end)
    {
        yield return date;
        date = date.AddDays(1);
    }
}

Usage:

DateTime startDate = new DateTime(2013, 1, 25);
DateTime endDate = new DateTime(2013, 1, 31);

foreach(var date in startDate.GetDatesTo(endDate))
    Console.WriteLine(date);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1
using System;
using System.Collections.Generic;

namespace Demo
{
    public static class Program
    {
        public static void Main()
        {
            foreach (var date in DateRange(new DateTime(2013, 01, 25), new DateTime(2013, 01, 31)))
            {
                Console.WriteLine(date.ToShortDateString());
            }
        }

        public static IEnumerable<DateTime> DateRange(DateTime start, DateTime end)
        {
            for (DateTime date = start; date <= end; date = date.AddDays(1))
            {
                yield return date;
            }
        }
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

linq version

        DateTime[] dates = { /*...25/01/2013, 26/01/2013*/ };
        DateTime start = DateTime.Parse("25/01/2013");
        DateTime end = DateTime.Parse("31/01/2013");
        var q = (from a in dates
                 where a.Date >= start.Date && a.Date <= end.Date
                 select a).ToList();
spajce
  • 7,044
  • 5
  • 29
  • 44