//根据年份计算该年有多少周
public static int GetWeekCountOfYear(int strYear)
{
DateTime firstDay = DateTime.Parse(strYear.ToString() + "-01-01");
int weekOfFirstDay = Convert.ToInt32(firstDay.DayOfWeek);//得到该年的第一天是星期几
int countWeek;//该年有多少周
//
//一年最少有53周,最多有54周
//如果是平年(365),52×7=364,多余1天,故共有53周
//如果是闰年(366),52×7=364,多余2天:
////如果多余的两天分别是年初和年末,则有54周,其他情况均为53周
//
if (DateTime.IsLeapYear(strYear) && weekOfFirstDay == 7)
{//如果该年是闰年且第一天为星期日
countWeek = 54;
}
else
{
countWeek = 53;
}
return countWeek;
}
//计算某天在某年的第几周内,且返回这周的起始日期
public int GetWeekOfCurrDate(DateTime dt)
{
int week = 0;//返回的周次
//获取该年有多少周
int countWeek = 0;
countWeek = GetWeekCountOfYear(dt.Year);
//获取该年有多少天
int countDay = 0;
if (!DateTime.IsLeapYear(dt.Year))
{
//平年
countDay = 365;
}
else
{
//闰年
countDay = 366;
}
//获取该年第一天是星期几
int firstDayOfWeek = (int)DateTime.Parse(dt.Year.ToString() + "-01-01").DayOfWeek;
//获取该年最后一天是星期几
int lastDayOfWeek = (int)DateTime.Parse(dt.Year.ToString() + "-12-31").DayOfWeek;
//获取第一周有多少天
int countDayOfFirstWeek = 7 - firstDayOfWeek + 1;
//获取最后一周有多少天
int countDayOfLastWeek = lastDayOfWeek;
//除去第一周和最后一周,该年还剩多少天
int countDayRemain = countDay - countDayOfFirstWeek - countDayOfLastWeek;
//除去第一周和最后一周,该年还剩多少周
int countWeekRemain = countDayRemain % 7;
if (dt.DayOfYear <= countDayOfFirstWeek)
{
//所求的日期在第一周内
week = 1;
}
else
{
if (dt.DayOfYear >= countDay - countDayOfLastWeek)
{
//所求的日期在最后一周内
week = countWeek - 2;
}
else
{
//判断除去第一周,所求日期是否能被7整除
if ((dt.DayOfYear - countDayOfFirstWeek) / 7 == 0)
{
week = (dt.DayOfYear - countDayOfFirstWeek) / 7 + 1;
}
else
{
week = (dt.DayOfYear - countDayOfFirstWeek) / 7 + 2;
}
}
}
return week;
}