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

本文介绍了一个改进的获取当前日期所在周数的方法,通过计算与上周末的天数差,准确地确定所在周数。同时,考虑了跨年情况,确保计算结果的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
  
 1         /// <summary>
 2         /// 获得今天是今年的第几周
 3         /// </summary>
 4         /// <param name="year"></param>
 5         /// <returns></returns>
 6         public string GetWeekOfYear(DateTime today)
 7         {
 8            int days = today.DayOfYear;           
 9            int remainder = days % 7;
10            if (remainder == 0)
11                return Convert.ToString(days / 7);
12             else
13                return Convert.ToString(days / 7 + 1); 
14         }
 
  

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

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

 1         public string GetWeekOfYear(DateTime today)
 2         {
 3            int weeknow = Convert.ToInt32(today.DayOfWeek);//today是周几  
 4            int daydiff = (-1) * (weeknow + 1);//今日与上周末的天数差   
 5            int days = today.AddDays(daydiff).DayOfYear;//上周末是本年第几天   
 6            int weeks = days / 7;
 7            if (days % 7 != 0)
 8            {
 9                weeks++;
10            }
11            //此时,weeks为上周是本年的第几周   
12            return Convert.ToString(weeks + 1); 
13         }

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

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

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

 1         /// <summary>
 2         /// 获得今天是今年的第几周
 3         /// </summary>
 4         /// <param name="today"></param>
 5         /// <returns></returns>
 6         public string GetWeekOfYear(DateTime today)
 7         {
 8             int NewYear = Convert.ToInt32(today.Year); //今年的年份
 9             int weeknow = Convert.ToInt32(today.DayOfWeek);//today是周几  
10             int daydiff = (-1 * weeknow);//今日与上周末的天数差   
11             int days = today.AddDays(daydiff).DayOfYear;//上周末是本年第几天   
12             int OldYear = Convert.ToInt32(today.AddDays(daydiff).Year); //上周末的年份
13             if (NewYear == OldYear)
14             {
15                int weeks = days / 7;
16                if (days % 7 != 0)
17                {
18                    weeks++;
19                }
20                //此时,weeks为上周是本年的第几周   
21                return Convert.ToString(weeks + 1);
22             }
23             else
24                return "1";
25         }

 

 

 

 

转载于:https://www.cnblogs.com/lhy5678888/p/3771836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值