已某个时间单位(日月周年)来分割时间段
public ListGetRangesByUnit(string unit, DateTime start, DateTime end) { //根据单位获取时间段的数组 unit:M,W,D List list = new List (); //获取两个时间相差的天数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; }
【已某个时间单位(日月周年)来分割时间段】转载于:https://www.cnblogs.com/ink-heart/p/8134023.html
推荐阅读
- 第三节|第三节 快乐和幸福(12)
- 20170612时间和注意力开销记录
- 时间老了
- 一粒饥饿不堪的米
- Eddy小文
- C语言中的时间函数clock()和time()你都了解吗
- Linux下面如何查看tomcat已经使用多少线程
- 山香|山香 善思 智学访谈
- 请给时间一点时间
- 全过程工程咨询——时间管理(12)