取当前日期是在一年中的第几周

C#里有GregorianCalendar这样一个类,只需要两行代码:

using System.Globalization;

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

    
写成通用的方法,获取某一日期是该年中的第几周

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上遇到这样一个问题,就是计算某一年有多少周,同样可以用这个类的方法来解决

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);  //该年星期数
}
原文地址:https://www.cnblogs.com/scorpio-qian/p/6144064.html