C# 获取日期为当年的第几周和周范围

网上看了一大堆方法,最后简单几行代码就可以搞定了,记录一下,没准还能帮助同行

1.代码如下

/// <summary>
///  获取时间的周范围 如:2022-35(周) 08-29~09-04
/// </summary>
string getDateWeekRang(DateTime tmpDate)
{
    var startDateStr = tmpDate.Date.AddDays(-(int)(tmpDate.DayOfWeek) + 1).ToString("yyyy-MM-dd");//当前周的开始日期
    var endDateStr = tmpDate.Date.AddDays(7 - (int)(tmpDate.DayOfWeek)).ToString("yyyy-MM-dd");//当前周的结束日期   
    GregorianCalendar gc = new System.Globalization.GregorianCalendar();
    int weekOfYear = gc.GetWeekOfYear(tmpDate, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
    return $"{tmpDate.Year}-{weekOfYear}(周) {startDateStr}~{endDateStr}";
}

2.效果图如下

posted @ 2022-09-05 16:39  peng_boke  阅读(720)  评论(0编辑  收藏  举报