首页 > 代码库 > .Net 获取日期所属于一年中的第几周

.Net 获取日期所属于一年中的第几周

关键代码:
public static int WeekOfYear(DateTime dt, CultureInfo ci)
{
//强制设置周一是每周的第一天
return ci.Calendar.GetWeekOfYear(dt, ci.DateTimeFormat.CalendarWeekRule, DayOfWeek.Monday);
//根据区域性信息对象设置每周的第一天
//return ci.Calendar.GetWeekOfYear(dt, ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek);
}

调用例子:

CultureInfo cultInfo = CultureInfo.GetCultureInfo("zh-CN");
int week = WeekOfYear(DateTime.Now, cultInfo);
Console.WriteLine("Date={0},WeekOfYear={1},day ( of the week) is={2}", DateTime.Now.ToString(), week, DateTime.Now.DayOfWeek.ToString());

string dateStr = "2017-01-01";
DateTime date1 = DateTime.Parse(dateStr, cultInfo.DateTimeFormat);
week = WeekOfYear(date1, cultInfo);
Console.WriteLine("Date={0},WeekOfYear={1},day ( of the week) is={2}", dateStr, week,date1.DayOfWeek.ToString());

dateStr = "2017-12-31";
date1 = DateTime.Parse(dateStr, cultInfo.DateTimeFormat);
week = WeekOfYear(date1, cultInfo);
Console.WriteLine("Date={0},WeekOfYear={1},day ( of the week) is={2}", dateStr, week, date1.DayOfWeek.ToString());

输出结果:

技术分享

 

.Net 获取日期所属于一年中的第几周