利用DateTime與小技巧來取得一週的開始與結束日期
這個範例主要是取得一週的開始與結束日期
透過兩個參數(某年,某週)就可以得知開始與結束日期
01 protected void Page_Load(object sender, EventArgs e)
02 {
03
04 //設定年
05 int year = 2007;
06
07 //設定週
08 int week = 30;
09
10 DateTime firstDay = new DateTime(year, 1, 1);
11
12 int add = 0;
13
14 switch (firstDay.DayOfWeek)
15 {
16 case DayOfWeek.Monday:
17 add = -1;
18 break;
19 case DayOfWeek.Tuesday:
20 add = -2;
21 break;
22 case DayOfWeek.Wednesday:
23 add = -3;
24 break;
25 case DayOfWeek.Thursday:
26 add = -4;
27 break;
28 case DayOfWeek.Friday:
29 add = -5;
30 break;
31 case DayOfWeek.Saturday:
32 add = -6;
33 break;
34 case DayOfWeek.Sunday:
35 add = 0;
36 break;
37 }
38
39 DateTime result1 = new DateTime(year, 1, 1).AddDays((week - 1) * 7).AddDays(add);
40 DateTime result2 = new DateTime(year, 1, 1).AddDays((week * 7) - 1).AddDays(add);
41
42 Response.Write(result1.ToShortDateString());
43 Response.Write(",");
44 Response.Write(result2.ToShortDateString());
45
46 }
02 {
03
04 //設定年
05 int year = 2007;
06
07 //設定週
08 int week = 30;
09
10 DateTime firstDay = new DateTime(year, 1, 1);
11
12 int add = 0;
13
14 switch (firstDay.DayOfWeek)
15 {
16 case DayOfWeek.Monday:
17 add = -1;
18 break;
19 case DayOfWeek.Tuesday:
20 add = -2;
21 break;
22 case DayOfWeek.Wednesday:
23 add = -3;
24 break;
25 case DayOfWeek.Thursday:
26 add = -4;
27 break;
28 case DayOfWeek.Friday:
29 add = -5;
30 break;
31 case DayOfWeek.Saturday:
32 add = -6;
33 break;
34 case DayOfWeek.Sunday:
35 add = 0;
36 break;
37 }
38
39 DateTime result1 = new DateTime(year, 1, 1).AddDays((week - 1) * 7).AddDays(add);
40 DateTime result2 = new DateTime(year, 1, 1).AddDays((week * 7) - 1).AddDays(add);
41
42 Response.Write(result1.ToShortDateString());
43 Response.Write(",");
44 Response.Write(result2.ToShortDateString());
45
46 }