在软件开发过程中,我们常常会遇到让用户根据日期条件进行查询的问题。通常,我们会放置两个DateTimePicker控件让用户自由选择。但是,如果用户需要经常查询指定期间的数据,那么分别指定期间的起止日期就会比较繁琐。如果我们能将常用的几个标准期间预置到软件中,则会让用户方便不少。下面是我的解决方案:
/// <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;
}
}
//调用示例
DateTime beginDate, endDate;
GetPeriod(Period.Year, out beginDate, out endDate);