获取一段时间的周数(过星期日算一周)

计算一段时间的周数,将开始时间和结束时间作为参数传到一个封装的方法中即可计算。这里是通过判断开始时间的星期和结束时间的星期计算得出的结果。

public int GetWeekCount(DateTime startTime,DateTime endTime)
        {
            //获取开始时间的星期一
            int startWeek = Convert.ToInt32(startTime.DayOfWeek);
            //因为是以星期一为第一天,所以要判断weeknow等于0时,要向前推6天。
            startWeek = (startWeek == 0 ? (7 - 1) : (startWeek - 1));
            int daydiff = (-1) * startWeek;
            string firstDay = startTime.AddDays(daydiff).ToString("yyyy-MM-dd");
            DateTime startMonday = Convert.ToDateTime(firstDay);
            //获取结束时间的星期日
            int lastWeek = Convert.ToInt32(endTime.DayOfWeek);
            int daydiff1 = 0;
            if (lastWeek != 0)
            {
                daydiff1 = 7 - lastWeek;
            }
            //本周最后一天
            string lastDay = endTime.AddDays(daydiff1).ToString("yyyy-MM-dd");
            DateTime lastSunday = Convert.ToDateTime(lastDay);
            TimeSpan timeSpan= (lastSunday - startMonday);
            //返回总周数
            return Convert.ToInt32(span1.Days + 1) / 7;
        }

根据周次来反查出本周次的开始时间和结束时间

 public (DateTime startDate, DateTime endDate) GetDateByZC(TimeFrame entity, int zc)
        {
            List<DateTime> list = new List<DateTime>();
            for (DateTime d = entity.XQQZSJ.Value; d <= entity.XQJSSJ.Value; d = d.AddDays(1))
            {
                list.Add(d);
            }
            while (list.First().DayOfWeek != DayOfWeek.Monday)
            {
                list.Insert(0, list.First().AddDays(-1));
            }

            list = list.OrderByDescending(x => x).ToList();
            while (list.First().DayOfWeek != DayOfWeek.Sunday)
            {
                list.Insert(0, list.First().AddDays(1));
            }
            list = list.OrderBy(x => x).ToList();

            DateTime startDate = list[(zc - 1) * 7];
            DateTime endDate = list[(zc - 1) * 7 + 6];

            while (startDate < entity.XQQZSJ)
            {
                startDate = startDate.AddDays(1);
            }
            while (endDate > entity.XQJSSJ)
            {
                endDate = endDate.AddDays(-1);
            }

            endDate = DateTime.Parse(endDate.ToString("yyyy-MM-dd") + " 23:59:59");

            return (startDate, endDate);
        }
上一篇:php 获取指定日期段内每一天的日期


下一篇:从0到1精通自动化测试,pytest自动化测试框架,allure2生成html报告(史上最详细)(九)