//根據年份計算該年有多少周
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;
}