使用当前日期作为参考获取特定日期
我想通过使用当前日期来获取两个特定日期,让我解释一下。
例如,如果今天是 10/27/2011 那么我想要 7/01/2011 和 9/30/2011。请注意,这是三个月的期限(不包括当月),我该怎么做?
目前我正在遵循自己设计的方法,但我认为它还很不好。这是代码。
TimeSpan TSFrom = new TimeSpan(90 + DateTime.Now.Day, 0, 0, 0, 0);
TimeSpan TSTo = new TimeSpan(DateTime.Now.Day, 0, 0, 0, 0);
Response.Write(DateTime.Now.Subtract(TSFrom).ToShortDateString());
Response.Write(DateTime.Now.Subtract(TSTo).ToShortDateString());
此代码返回这些值
7/2/2011 - 9/30/2011
,虽然它有些可以接受,但它看起来仍然不是一个完美的方式,看起来第一个日期是从每月的第二天开始,而它应该从第一天开始日,我认为这是因为有些月份在 29 日结束,而有些月份在 30 日结束。那么我怎样才能获得像 7/1/2011 到 9/30/2011 这样的完美日期。
谢谢。
I want to get two particular dates by using current date, let me explain more.
For example if today is 10/27/2011 then I would like to have 7/01/2011 and 9/30/2011. Note that its a three month period (excluding current month) How can I do that ?
Currently I am following a self designed method but I think its far from good. Here is the code.
TimeSpan TSFrom = new TimeSpan(90 + DateTime.Now.Day, 0, 0, 0, 0);
TimeSpan TSTo = new TimeSpan(DateTime.Now.Day, 0, 0, 0, 0);
Response.Write(DateTime.Now.Subtract(TSFrom).ToShortDateString());
Response.Write(DateTime.Now.Subtract(TSTo).ToShortDateString());
This code return these values
7/2/2011 - 9/30/2011
while its some what acceptable its still looks like not a perfect way to go and look the first date is starting from the second day of month while it should start from first day, I think its because some months end on 29 while some on 30. So how can I get the perfect dates like 7/1/2011 to 9/30/2011.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(您可以将
new DateTime(now.Year, now.Month, 1)
存储在局部变量中,我想这是个人品味的问题......)(You could store
new DateTime(now.Year, now.Month, 1)
in a local variable, this is a matter of personal taste, I guess ...)我们通过减去(当前日期 - 1)来“回滚”到月初,
周期结束时间为
firstOfMonth.AddDays(-1);
,周期开始时间为firstOfMonth.AddMonths(-3);
We "roll back" to the beginning of the month by subtracting the (current day - 1),
the end of the period is
firstOfMonth.AddDays(-1);
, the beginning of the period isfirstOfMonth.AddMonths(-3);
它可以更短但可读性较差
It could be even shorter but less readable