简体   繁体   中英

Given a start and end date… find all dates within range in C#

Given DateTime start = startsomething and DateTime end = endSomething

Is there a standard way to return all Dates within start and end such that the return is a list of Dates like ...

'1/1/2012 12:00 AM'
'1/2/2012 12:00 AM'

You can create a method like this:

public static IEnumerable<DateTime> Range(DateTime start, DateTime end) {
  for (var dt = start; dt <= end; dt = dt.AddDays(1)) {
    yield return dt;
  }
}

You can fill a list with all the dates:

DateTime begin = //some start date
DateTime end = //some end date
List<DateTime> dates = new List<DateTime>();
for(DateTime date = begin; date <= end; date = date.AddDays(1))
{
    dates.Add(date);
}

The Linq way:

DateTime start = new DateTime(2012, 1, 1);
DateTime end = new DateTime(2012, 6, 1);

var list = Enumerable.Range(0, (end - start).Days + 1).Select(i => start.AddDays(i));

You can use this for generating a date range

public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
  if (endDate < startDate)
    throw new ArgumentException("endDate must be greater than or equal to startDate");

  while (startDate <= endDate)
  {
    yield return startDate;
    startDate = startDate.AddDays(1);
  }
}

Then

GetDateRange(startDate,endDate).Select(d => d.ToString("dd/MM/yyyy hh:mm")).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM