在C#中获取两个'DateTime'之间的所有DateTimes


76

我有两个DateTimeS,我想得到全部DateTime在这些日期之间。例如,如果我的日期类似于01.01.2010-05.01.2010,则我的函数应返回一个日期列表(列表),并且必须包含01.01.2010、02.01.2010、03.01.2010、04.01.2010和2010年5月1日。

我写了这样的函数。如果我的约会在一个月之内,它就可以正常工作。如果我的约会日期为01.01.2010-05.02.2010,则无法使用。因为月份改变了,所以我的功能无法处理它。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));
        }

问题已解决,请参阅蒂姆·罗宾逊的简单答案。

Answers:


133

您可以DateTime在循环中直接使用对象来代替intDateTime.AddDays正确处理月末。

for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
    allDates.Add(date);

74

这样的事情怎么样?

public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
{
    return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
                     .Select(d => fromDate.AddDays(d));
}

编辑:现在测试。:)


正是我所需要的。可行,真的很干净。
gligoran

9
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);
    }
}

应该很好地利用产量。
Jamiec

4

您是如此亲密...只是不使用日期,而是使用整个日期。

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

1

这是一个快速的控制台应用程序,以演示如何进行操作-AddDays()改为使用:

class Program
{
    static void Main(string[] args)
    {

        GetDates(new DateTime(2010, 1, 1), new DateTime(2010, 2, 5));

        Console.ReadKey();
    }

    static List<DateTime> GetDates(DateTime startDate, DateTime endDate)
    {
        List<DateTime> dates = new List<DateTime>();

        while ((startDate = startDate.AddDays(1)) < endDate)
        {
            dates.Add(startDate);
        }

        return dates;
    }
}

该死,对此有很多答案。
slugster 2010年

1

给定String中较低的日期值和较高的日期值,并以频率作为第三个参数,此方法应返回日期字典;其中键是日期范围的起始值,而值是相应范围。如果频率是每周或每月,则效果很好-您可以根据需要自定义频率。传递的日期值应采用正确的格式,或者您可能需要使用tryParseExact或类似的格式对其进行格式化。

    protected static Dictionary<DateTime, String> getDateRange(String lowerDate, String higherDate, String frequency)
    {
        DateTime startDate, endDate;
        startDate = Convert.ToDateTime(lowerDate);
        endDate = Convert.ToDateTime(higherDate);

        Dictionary<DateTime, String> returnDict = new Dictionary<DateTime, String>();

        while (frequency.Equals("weekly") ? (startDate.AddDays(7) <= endDate) : (startDate.AddMonths(1) <= endDate))
        {
            if (frequency.Equals("weekly"))
            {
                returnDict.Add(startDate, startDate + "-" + startDate.AddDays(7));
                startDate = startDate.AddDays(8);
            }
            if (frequency.Equals("monthly"))
            {
                returnDict.Add(startDate, startDate + "-" + startDate.AddMonths(1));
                startDate = startDate.AddMonths(1).AddDays(1);
            }
        }

        returnDict.Add(startDate, startDate + "-" + endDate);

        return returnDict;
    }

请格式化代码,以便函数的第一行也被格式化为代码。这个答案不能解决问题,因为他写道他已经有两个DateTimes并想要一个List,但是您的函数使用字符串而不是DateTimes并返回Dictionary而不是list。另外,他希望开始日期和结束日期之间的每个日期,而不是每周一次或每月一次。
tomsv

1

如果日期包含不同的时间,则最佳解决方案将失败。这是一个可以全天候工作的解决方案:

每天:

static public List<string> get_days_between_two_dates(DateTime start_date, DateTime end_date)
    {
        List<string> days_list = new List<string>();
        DateTime temp_start;
        DateTime temp_end;

        //--Normalize dates by getting rid of minues since they will get in the way when doing the loop
        temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day);
        temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day);

        //--Example Should return
        //--1-12-2014 5:59AM - 1-13-2014 6:01AM return 12 and 13
        for (DateTime date = temp_start; date <= temp_end; date = date.AddDays(1))
        {
            days_list.Add(date.ToShortDateString());
        }

        return days_list;
    }

所有时间:

static public List<string> get_hours_between_two_dates(DateTime start_date, DateTime end_date)
    {
        List<string> hours_24_list = new List<string>();
        DateTime temp_start;
        DateTime temp_end;

        //--Normalize dates by getting rid of minutes since they will get in the way when doing the loop
        temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day, start_date.Hour, 0, 0);
        temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day, end_date.Hour, 0, 0);

        //--Example Should return
        //--5:59AM - 6:01AM return 5am and 6am
        for (DateTime date = temp_start; date <= temp_end; date = date.AddHours(1))
        {
            hours_24_list.Add(date.ToShortTimeString());
        }

        return hours_24_list;
    }

0
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();
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.