取當前日期是在一年中的第幾周

C#裏有GregorianCalendar這樣一個類,只須要兩行代碼:

spa

using System.Globalization;

GregorianCalendar gc = new GregorianCalendar();
int weekOfYear = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

    
寫成通用的方法,獲取某一日期是該年中的第幾周

io

using System.Globalization;

/// <summary>
/// 獲取某一日期是該年中的第幾周
/// </summary>
/// <param name="dt">日期</param>
/// <returns>該日期在該年中的週數</returns>
private int GetWeekOfYear(DateTime dt)
{
    GregorianCalendar gc = new GregorianCalendar();
    return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}


    之前還在CSDN上遇到這樣一個問題,就是計算某一年有多少周,一樣能夠用這個類的方法來解決

gc

using System.Globalization; /// <summary> /// 獲取某一年有多少周 /// </summary> /// <param name="year">年份</param> /// <returns>該年週數</returns> private int GetWeekAmount(int year) {     DateTime end = new DateTime(year, 12, 31);  //該年最後一天     System.Globalization.GregorianCalendar gc = new GregorianCalendar();     return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday);  //該年星期數 }
相關文章
相關標籤/搜索