点关注不迷路

Max

DateHelper

public static class DateHelp
    {
        /// <summary>
        /// 获取当前日期是该月的第几周
        /// </summary>
        /// <param name="dateNow"></param>
        /// <returns>该日期所在周是第几周</returns>
        public static int WeekOfMonth(DateTime dateNow)
        {
            DateTime StartDate = new DateTime(dateNow.Year, dateNow.Month, 1);
            DateTime EndDate = StartDate.AddMonths(1).AddDays(-1);
            int WeekIndex = 1;
            TimeSpan ts = dateNow - StartDate;
            DateTime TempDate = StartDate;
            if (TempDate.DayOfWeek == System.DayOfWeek.Monday)
                TempDate = TempDate.AddDays(1);
            while (TempDate <= EndDate)
            {
                if (TempDate.DayOfWeek == System.DayOfWeek.Monday && dateNow.ToString("yyyy-MM-dd") != StartDate.ToString("yyyy-MM-dd"))
                {
                    WeekIndex++;
                }
                if (TempDate.ToString("yyyy-MM-dd") == dateNow.ToString("yyyy-MM-dd"))
                {
                    break;
                }
                TempDate = TempDate.AddDays(1);
            }

            return WeekIndex;

        }

        /// <summary>
        /// 获取当前日期所在周的周一日期
        /// </summary>
        /// <param name="dateNow"></param>
        /// <returns></returns>
        public static DateTime? GetStartWeekDate(DateTime dateNow)
        {
            for (int i = 0; i < 7; i++)
            {
                DateTime temp = dateNow.AddDays(i * (-1));
                if (temp.DayOfWeek == System.DayOfWeek.Monday)
                    return temp;
            }
            return null;
        }
        /// <summary>
        /// 获取当前日期所在周的周日日期
        /// </summary>
        /// <param name="dateNow"></param>
        /// <returns></returns>
        public static DateTime? GetEndWeekDate(DateTime dateNow)
        {
            for (int i = 0; i < 7; i++)
            {
                DateTime temp = dateNow.AddDays(i);
                if (temp.DayOfWeek == System.DayOfWeek.Sunday)
                    return temp;
            }
            return null;
        }
    }

 

posted @ 2018-04-28 15:44  Max麦克斯  阅读(231)  评论(0编辑  收藏  举报