求每个年,月,周的起始日期和结束日期
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, 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;
}
}
/// 声明期间类型枚举
/// </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;
}
}
作者:蓝之风
出处:http://www.cnblogs.com/vaiyanzi/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。