本文以系统时间为例,只要对比较的时间点作改变,即可对特定日期获取起至年、月和周
详细代码
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);