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


 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         }

 

 

 

 

posted @ 2014-06-06 09:23  林海云  阅读(670)  评论(0编辑  收藏  举报