从日期时间生成相对日期范围(本周、今年、上个月等)的最佳方法是什么?
我确信我不是第一个需要这样做的人,所以我正在寻找最好的方法。
我有一组单选按钮,其中包含诸如今年去年本月上个月本周上周等选项
- 我
- 需要
- 从
- 日期
- 当前
- ,
生成正确的相对日期范围(DateTime.Now
)。
例如,如果选择了去年
并且当前日期为4/2/09 14:45:32
,我需要返回开始日期1/ 1/08 00:00:00
和结束日期 12/31/08 23:59:59
。
有什么想法吗?
I'm sure I'm not the first person to need to do this, so I'm looking for the best way.
I've got a set of radio buttons with choices such as
- This Year
- Last Year
- This Month
- Last Month
- This Week
- Last Week
and I need to produce the proper relative date range from the current date (DateTime.Now
).
For example if Last Year
was selected and the current date was 4/2/09 14:45:32
I would need to return a start date of 1/1/08 00:00:00
and end date of 12/31/08 23:59:59
.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
所有这些都已使用 DateTime.Today 进行了测试,并且按照您的要求工作:
All of these have been tested using DateTime.Today, and work just like you asked for:
今年:
本月: 本周
:
去年/月/周是上述的简单变化。 编辑: 本周假设本周从周日开始。 如果您的星期从星期一开始,您将需要稍微修改代码。
This year:
This month:
This week:
Last year / month / week are simple variations on above. Edit: This week assumes the week starts on Sunday. You would have to modify the code slightly if your weeks start on Monday.
我将创建一个工厂方法,该方法将返回一个接口(或您可以执行的委托),该接口将传递当前日期并根据实现返回日期范围。
当然,您从工厂方法返回的实现将由您传递给它的枚举值决定,该枚举对应于“今年”、“去年”等。
I would create a factory method which will return an interface (or a delegate which you can execute) which would be passed the current date and return the date range for you based on the implementation.
Of course, which implementation you return from the factory method would be determined by the value of an enumeration you pass to it which corresponds to "this year", "last year", etc, etc.
我将使用 DateTime 内置方法添加和返回日期的特定部分来编写一个返回间隔的函数。
I would use the DateTime built-in methods for Adding and returning specific portions of the date to write a function that would return the interval.