我有两个DateTime,我想DateTime在这些日期之间得到所有.例如,如果我的日期类似于01.01.2010 - 05.01.2010,我的函数应该返回一个日期列表(列表),它必须包含01.01.2010,02.01.2010,03.01.2010,04.01.2010,并且05.01.2010.
我写了这样的函数.如果我的约会在一个月内,它工作正常.如果我的约会日期是2010年1月1日至2010年5月5日,则不起作用.因为月份改变了,我的功能无法处理.C#中是否有一个函数返回两个日期之间的所有日期?或者我该如何处理月份变化?
public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
int starting = startingDate.Day;
int ending = endingDate.Day;
for (int i = starting; i <= ending; i++)
{
allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i));
}
Run Code Online (Sandbox Code Playgroud)
问题解决了,看Tim Timinson的简单回答.
Tim*_*son 124
您可以DateTime直接在循环中使用对象,代替您的对象int.DateTime.AddDays处理月份正确结束.
for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
allDates.Add(date);
Run Code Online (Sandbox Code Playgroud)
Mat*_*ton 66
这样的事怎么样?
public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
{
return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
.Select(d => fromDate.AddDays(d));
}
Run Code Online (Sandbox Code Playgroud)
编辑:现在测试.:)
public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
if (endingDate < startingDate)
{
throw new ArgumentException("endingDate should be after startingDate");
}
var ts = endingDate - startingDate;
for (int i = 0; i < ts.TotalDays; i++)
{
yield return startingDate.AddDays(i);
}
}
Run Code Online (Sandbox Code Playgroud)
你是如此接近......只是不要使用这一天,使用整个日期。
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58108 次 |
| 最近记录: |