给定DateTime start = startsomething
和DateTime end = endSomething
是否有一种标准的方法可以在开始和结束时返回所有日期,以便返回的日期列表如...
'1/1/2012 12:00 AM'
'1/2/2012 12:00 AM'
答案 0 :(得分:5)
您可以创建一个这样的方法:
public static IEnumerable<DateTime> Range(DateTime start, DateTime end) {
for (var dt = start; dt <= end; dt = dt.AddDays(1)) {
yield return dt;
}
}
答案 1 :(得分:3)
您可以填写包含所有日期的列表:
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);
}
答案 2 :(得分:3)
Linq方式:
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));
答案 3 :(得分:0)
您可以使用它来生成日期范围
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);
}
}
然后
GetDateRange(startDate,endDate).Select(d => d.ToString("dd/MM/yyyy hh:mm")).ToArray();