根据当前时间计算周次!(每年的第一天属于第一周 C#实现)
//年份、月份、周次
//每周的一天可以自行设置
//测试以每周周一为每周的第一天
//2012年1月1日 周日 属于2012年的第一周,2011年12月26日至2011年12月31日属于2012年的第一周。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static string getWeek(DateTime dtime)
2 {
3 int nowWeekindex=0;
4 string yearmonthweek="";
5 int dayofyear=dtime.DayOfYear;
6 int dayofmonth=dtime.Month;
7 int dayofweek=(int)dtime.DayOfWeek;
8 DateTime dtfirstday=new DateTime(dtime.Year,1,1);
9 int dtfirstdayofweek=(int)dtfirstday.DayOfWeek;
10 DateTime dtlastday=new DateTime(dtime.Year,12,31);
11 DateTime dtnextyear=new DateTime(dtime.Year+1,1,1);
12 int dtnextyeardayofweek=(int)dtnextyear.DayOfWeek;
13 int nextyear=sy(dtnextyear)-1;
14 DateTime dtlastday1=new DateTime(dtime.Year,12,31-nextyear);
15 if((int)dtime.DayOfYear-(int)dtfirstday.DayOfYear<=7-sy(dtfirstday))
16 {
17 nowweekindex=1;
18 yearmonthweek=dtime.Year+"_"+dayofmonth+"_"+nowweekindex;
19 }
20 else if((int)dtime.DayOfYear<=(int)dtlastday1.DayOfYear)
21 {
22 for(int j=0;j<aweek.Length;j++)
23 {
24 if(Convert.ToInt32(aweek[j])==dtfirstdayofweek)
25 {
26 int b=aweek.Length-(j+1);
27 int x=(dayofyear-1)-b;
28 int weekd=x/7;
29 int yushu=x%7;
30 if(yushu!=0)
31 {
32 nowweekindex=weekd+2;
33 yearmonthweek=dtime.Year+"_"+dayofmonth+"_"+nowweekindex;
34 }
35 else
36 {
37 nowweekindex=weekd+1;
38 yearmonthweek=dtime.Year+"_"+dayofmonth+"_"+nowweekindex;
39 }
40 }
41 }
42 }
43 else
44 {
45 nowweekindex=weekd+1;
46 yearmonthweek=dtime.Year+1+"_"+1+"_"+nowweekindex;
47 }
48 return yearmonthweek;
49 }
50
51 public static int sy(DateTime dtime)
52 {
53 int midnum=0;
54 int midof=(int)dtime.DayOfWeek;
55 for(int i=0;i<aweek.Length;i++)
56 {
57 if(Convert.ToInt32(aweek[i])==midof)
58 {
59 midnum=i;
60 }
61 }
62 return midnum+1;
63 }
在此程序中aweek为一周内星期顺序。
例如:周日为每周的第一天则aweek序列为0,1,2,3,4,5,6 周一为每周第一天则aweek序列为1,2,3,4,5,6,0
大家可以想一下,计算总周次怎么来做!