获取当天是当年/当月的第几周

 

引用名称空间:

using System.Globalization;

 

示例代码:

 DateTime date = DateTime.Now;
 
            //获取指定时间是当年的第几周
            GregorianCalendar gc = new GregorianCalendar();
            int weekOfYear = gc.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            Console.WriteLine("{0}是当年的第{1}周", date.ToString("yyyy年MM月dd日"), weekOfYear);
            Console.ReadKey();
 
            //获取是当月的第几周
            int dayInMonth = date.Day;
            //本月第一天  
            DateTime firstDay = date.AddDays(1 - date.Day);
            //本月第一天是周几  
            int weekday = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;
            //本月第一周有几天  
            int firstWeekEndDay = 7 - (weekday - 1);
            //当前日期和第一周之差  
            int diffday = dayInMonth - firstWeekEndDay;
            diffday = diffday > 0 ? diffday : 1;
            //当前是第几周,如果整除7就减一天  
            int WeekNumInMonth = ((diffday % 7) == 0
             ? (diffday / 7 - 1)
             : (diffday / 7)) + 1 + (dayInMonth > firstWeekEndDay ? 1 : 0);
            Console.WriteLine("{0}是当月的第{1}周", date.ToString("yyyy年MM月dd日"), WeekNumInMonth);
            Console.ReadKey();

 

posted @ 2018-03-20 17:58  秋刀鱼No1  阅读(3130)  评论(0编辑  收藏  举报