Getting all DateTimes between two 'DateTime's in C#

前端 未结 8 652
清酒与你
清酒与你 2020-12-12 20:14

I have two DateTimes, and I want to get all DateTimes between these Dates. Such as, if my Dates are like 01.01.2010 - 05.01.2010, my function shoul

8条回答
  •  粉色の甜心
    2020-12-12 20:40

    Given a lowerdate value and higher date value in String and a frequency as the third parameter this method should return a dictionary of dates; where the key is the start value of a date range and the value is the respective range. This works fine if the frequency is either weekly or monthly- you can customize it as per your need. The date values passed should be in proper format or you might need to format it using tryParseExact or something like that.

        protected static Dictionary getDateRange(String lowerDate, String higherDate, String frequency)
        {
            DateTime startDate, endDate;
            startDate = Convert.ToDateTime(lowerDate);
            endDate = Convert.ToDateTime(higherDate);
    
            Dictionary returnDict = new Dictionary();
    
            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;
        }
    

提交回复
热议问题