1、引用命名空间:
using System.Globalization;
2、代码:
//时间赋值
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();
//打印结果
//2017年03月01日是当年的第10周
//2017年03月01日是当月的第1周
///
/// 获取指定日期,在为一年中为第几周
///
/// 指定时间
///返回第几周
private static int GetWeekOfYear(DateTime dt)
{
GregorianCalendar gc = new GregorianCalendar();
int weekOfYear = gc.GetWeekOfYear(dt,CalendarWeekRule.FirstDay, DayOfWeek.Monday);
return weekOfYear;
}
//摘自 Xingsoft's blog