C# 中根据datetime的值来计算属于本年的第几周,类似delphi中的weekoftheyear功能

时间:2021-12-15 05:44:38

         /// <summary>
/// 获得今天是今年的第几周
/// </summary>
/// <param name="year"></param>
/// <returns></returns>
public string GetWeekOfYear(DateTime today)
{
int days = today.DayOfYear;
int remainder = days % ;
if (remainder == )
return Convert.ToString(days / );
else
return Convert.ToString(days / + );
}

-------------上面的代码没有考虑到当年的1月1号,并非是周一,所以算出来的会有误差

下面是参考博客园唔愛吃蘋果的代码。

         public string GetWeekOfYear(DateTime today)
{
int weeknow = Convert.ToInt32(today.DayOfWeek);//today是周几
int daydiff = (-) * (weeknow + );//今日与上周末的天数差
int days = today.AddDays(daydiff).DayOfYear;//上周末是本年第几天
int weeks = days / ;
if (days % != )
{
weeks++;
}
//此时,weeks为上周是本年的第几周
return Convert.ToString(weeks + );
}

他这边就巧妙的用上周末的来计算之前的周数

可是也存在比如本年的1月1号是周三,那么上周的周末是去年的,导致计算出错。

再加入判断,修改后代码如下:

         /// <summary>
/// 获得今天是今年的第几周
/// </summary>
/// <param name="today"></param>
/// <returns></returns>
public string GetWeekOfYear(DateTime today)
{
int NewYear = Convert.ToInt32(today.Year); //今年的年份
int weeknow = Convert.ToInt32(today.DayOfWeek);//today是周几
int daydiff = (- * weeknow);//今日与上周末的天数差
int days = today.AddDays(daydiff).DayOfYear;//上周末是本年第几天
int OldYear = Convert.ToInt32(today.AddDays(daydiff).Year); //上周末的年份
if (NewYear == OldYear)
{
int weeks = days / ;
if (days % != )
{
weeks++;
}
//此时,weeks为上周是本年的第几周
return Convert.ToString(weeks + );
}
else
return "";
}