引用名稱空間:
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();
