我敢肯定我不是第一个需要这样做的人,所以我正在寻找最好的方法.
我有一组带有选项的单选按钮
今年
去年
这个月
上个月
本星期
上个星期
我需要从当前日期(DateTime.Now
)生成适当的相对日期范围.
例如,如果Last Year
选择了当前日期,则4/2/09 14:45:32
需要返回开始日期1/1/08 00:00:00
和结束日期12/31/08 23:59:59
.
有什么想法吗?
所有这些都已经使用DateTime.Today进行了测试,就像你要求的那样工作:
public struct DateRange { public DateTime Start { get; set; } public DateTime End { get; set; } } public static DateRange ThisYear(DateTime date) { DateRange range = new DateRange(); range.Start = new DateTime(date.Year, 1, 1); range.End = range.Start.AddYears(1).AddSeconds(-1); return range; } public static DateRange LastYear(DateTime date) { DateRange range = new DateRange(); range.Start = new DateTime(date.Year - 1, 1, 1); range.End = range.Start.AddYears(1).AddSeconds(-1); return range; } public static DateRange ThisMonth(DateTime date) { DateRange range = new DateRange(); range.Start = new DateTime(date.Year, date.Month, 1); range.End = range.Start.AddMonths(1).AddSeconds(-1); return range; } public static DateRange LastMonth(DateTime date) { DateRange range = new DateRange(); range.Start = (new DateTime(date.Year, date.Month, 1)).AddMonths(-1); range.End = range.Start.AddMonths(1).AddSeconds(-1); return range; } public static DateRange ThisWeek(DateTime date) { DateRange range = new DateRange(); range.Start = date.Date.AddDays(-(int)date.DayOfWeek); range.End = range.Start.AddDays(7).AddSeconds(-1); return range; } public static DateRange LastWeek(DateTime date) { DateRange range = ThisWeek(date); range.Start = range.Start.AddDays(-7); range.End = range.End.AddDays(-7); return range; }
今年:
DateTime Today = DateTime.Today; DateTime StartDate = new DateTime(Today.Year,1,1); DateTime EndDate = StartDate.AddYears(1).AddSeconds(-1);
这个月:
DateTime Today = DateTime.Today; DateTime StartDate = new DateTime(Today.Year,Today.Month,1); DateTime EndDate = StartDate.AddMonths(1).AddSeconds(-1);
本星期:
DateTime Today = DateTime.Today; DateTime StartDate = Today.AddDays(-((int) Today.DayOfWeek)); DateTime EndDate = StartDate.AddDays(7).AddSeconds(-1);
去年/月/周是上面的简单变化.编辑: 本周假设星期日开始.如果您的周数从周一开始,您将不得不稍微修改一下代码.