已某个时间单位(日月周年)来分割时间段
public List<RunningRange> GetRangesByUnit(string unit, DateTime start, DateTime end) { //根据单位获取时间段的数组 unit:M,W,D List<RunningRange> list = new List<RunningRange>(); //获取两个时间相差的天数 if ((end - start).Seconds < 0) { return list; } //单位日 if (unit == "D") { int days = (end - start).Days; for (int i = 0; i <= days; i++) { RunningRange range = new RunningRange(); range.Start = start.AddDays(i); range.End = range.Start.AddDays(1); list.Add(range); } } //单位周 if (unit == "W") { DateTime startWeek = start.AddDays(1 - Convert.ToInt32(start.DayOfWeek.ToString("d"))); DateTime endWeek = end.AddDays(1 + (7 - Convert.ToInt32(end.DayOfWeek.ToString("d")))); int weeks = (endWeek - startWeek).Days / 7; for (int i = 0; i <= weeks; i++) { RunningRange range = new RunningRange(); DateTime time = start.AddDays(6 * i); range.Start = time.AddDays(1 - Convert.ToInt32(time.DayOfWeek.ToString("d"))); range.End = range.Start.AddDays(7); list.Add(range); } } //单位月 if (unit == "M") { DateTime startMonth = start.AddDays(1 - start.Day); DateTime endMonth = end.AddDays(DateTime.DaysInMonth(end.Year, end.Month) - end.Month); int days = (endMonth - startMonth).Days; int MonthDays = 0; while (true) { DateTime tempdate = startMonth; MonthDays = DateTime.DaysInMonth(tempdate.Year, tempdate.Month); RunningRange range = new RunningRange(); range.Start = tempdate; range.End = range.Start.AddDays(MonthDays); list.Add(range); days -= MonthDays; if (days <= 0) { break; } startMonth = range.End; } } if (unit == "Y") { //获取时间的年的部分 int year = start.Year; int yearend = end.Year; for (int i = 0; i <= (yearend - year); i++) { RunningRange range = new RunningRange(); range.Start = new DateTime(year + i, 1, 1); range.End = range.Start.AddYears(1); list.Add(range); } } return list; }