c# 自然周

來源:互聯網
上載者:User
   //根據年份計算該年有多少周

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;

}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.