获取所有DateTimes之间的两个'DateTime's在C# [英] Getting all DateTimes between two 'DateTime's in C#
问题描述
我有两个 DateTime
s,我想在这些日期之间获取所有 DateTime
。例如,如果我的日期像01.01.2010 - 05.01.2010,我的函数应该给我一个日期列表(List),它必须包含01.01.2010,02.01.2010,03.01.2010,04.01.2010和05.01.2010。
I have two DateTime
s, and I want to get all DateTime
s between these Dates. Such as, if my Dates are like 01.01.2010 - 05.01.2010, my function should return me a list of date (List), and it must contain 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010, and 05.01.2010.
我写了一个这样的功能。工作正常,如果我的日期在一个月。如果我的日期像01.01.2010 - 05.02.2010那样不行。因为月份改变了,我的功能无法处理。 C#中是否有函数返回两个日期之间的所有日期?或者如何处理月份变化?
I wrote a function like this. It works fine, if my dates are in a month. It won't work if my dates are like 01.01.2010 - 05.02.2010. Because the month changed, and my function can't handle it. Is there a function in C# that returns all dates between two dates? Or how can I handle month change?
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));
}
问题已解决,请参阅Tim Robinson使用的简单答案。
Question solved, see Tim Robinson's simple answer to use.
推荐答案
您可以直接在循环中使用 DateTime
对象代替 int
。 DateTime.AddDays
正确处理月底。
You can use DateTime
objects directly in the loop, in place of your int
. DateTime.AddDays
handles month ends correctly.
for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
allDates.Add(date);
这篇关于获取所有DateTimes之间的两个'DateTime's在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!