代码改变世界

求每个年,月,周的起始日期和结束日期

2007-08-06 15:02  蓝之风  阅读(710)  评论(0编辑  收藏  举报

我们在写程序的时候往往要计算出年,月,周的开始日期和结束日期,在这里给出统一求解方法

/// <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, 11);
                    endDate 
= new DateTime(year, 1231); 
                    
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;
            }

        }