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}";
}