獲取當天是當年/當月的第幾周


 

引用名稱空間:

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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM