根据2段时间获取期间的每个周末日期和月末日期

  private DateTime WeekStartTime(DateTime dateTime)
        {

            DateTime dt = dateTime;
            int dayOfWeek = -1 * (int)dt.Date.DayOfWeek;

            DateTime weekStartTime = dt.AddDays(dayOfWeek + 1);//取本周一
            if (dayOfWeek == 0) //如果今天是周日,则开始时间是上周一
            {
                weekStartTime = weekStartTime.AddDays(-7);
            }
            return weekStartTime.Date;

        }
        private List<DateTime> GetSundays(DateTime start, DateTime end)
        {
            var startMonday = WeekStartTime(start);
            var startSunday = startMonday.AddDays(6);
            var endMonday = WeekStartTime(end);
            var endSunday = endMonday.AddDays(6);
            List<DateTime> list = new List<DateTime>();
            TimeSpan sp = endSunday.Subtract(startSunday);
            int dayCount = sp.Days;
            var ceil = Convert.ToInt32(Math.Ceiling(dayCount / (double)7));
            for (int i = 0; i <= ceil; i++)
            {
                var date = startSunday.AddDays(i * 7);
                if (i == ceil)
                {
                    if (date > end)
                    {
                        list.Add(end);
                        break;
                    }
                }
                list.Add(date);

            }
            return list;
        }
        private List<DateTime> GetYueMo(DateTime start, DateTime end)
        {
            DateTime startYueChu = start.AddDays(1 - start.Day);  //本月月初
            DateTime startYueMo = startYueChu.AddMonths(1).AddDays(-1);  //本月月末
            var endYueChu = end.AddDays(1 - end.Day);
            var endYueMo = endYueChu.AddMonths(1).AddDays(-1);
            List<DateTime> list = new List<DateTime>();
            TimeSpan sp = endYueMo.Subtract(startYueMo);
            int ms = (endYueMo.Year * 12 + endYueMo.Month) - (startYueMo.Year * 12 + startYueMo.Month);
            for (int i = 0; i <= ms; i++)
            {
                var date = startYueMo.AddMonths(i);
                if (i == ms)
                {
                    if (date > end)
                    {
                        list.Add(end);
                        break;
                    }
                }
                list.Add(date);

            }
            return list;
        }

  

posted on 2020-03-20 10:28  落叶子  阅读(210)  评论(0编辑  收藏  举报

导航