本文实例讲述了C#获取每个年,月,周的起始日期和结束日期的方法。分享给大家供大家参考,具体如下:
我们在写程序的时候往往要计算出年,月,周的开始日期和结束日期,在这里给出统一求解方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/// <summary> /// 声明期间类型枚举 /// </summary> public enum Period {Day, Week, Month, Year}; /// <summary> /// 获取指定期间的起止日期 /// </summary> /// <param name="period">期间类型</param> /// <param name="beginDate">开始日期</param> /// <param name="endDate">结束日期</param> public static void GetPeriod(Period period, out DateTime beginDate, out DateTime endDate) { int year = DateTime.Today.Year; int month = DateTime.Today.Month; switch (period) { case Period.Year: //年 beginDate = new DateTime(year, 1, 1); endDate = new DateTime(year, 12, 31); break ; case Period.Month: //月 beginDate = new DateTime(year, month, 1); endDate = beginDate.AddMonths(1).AddDays(-1); break ; case Period.Week: //周 int week = ( int )DateTime.Today.DayOfWeek; if (week == 0) week = 7; //周日 beginDate = DateTime.Today.AddDays(-(week - 1)); endDate = beginDate.AddDays(6); break ; default : //日 beginDate = DateTime.Today; endDate = DateTime.Today; break ; } } |
希望本文所述对大家C#程序设计有所帮助。