如何从开始日期和结束日期查找日期列表

时间:2013-01-25 10:36:33

标签: c# .net datetime

  

可能重复:
  Find missing dates for a given range
  Create an array or List of all dates between two dates

数据类型DateTime的两个日期代表date of startdate of end

我需要返回一个包含DateTime格式的所有日期的数组或List。

考虑性能原因的代码更快。任何人都可以通过示例源代码向我指出正确的方向吗?

实施例

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

4 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:1)

您可以创建扩展方法:

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

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

用法:

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

foreach(var date in startDate.GetDatesTo(endDate))
    Console.WriteLine(date);

答案 2 :(得分: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;
            }
        }
    }
}

答案 3 :(得分:0)

linq版

        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();