使用当前日期作为参考获取特定日期
本文关键字:获取 日期 参考 当前日期 | 更新日期: 2023-09-27 18:12:44
我想通过使用当前日期来获得两个特定的日期,让我来解释更多。
例如,如果今天是2011年10月27日,那么我希望是2011年1月7日和2011年9月30日。请注意,这是一个三个月的期限(不包括本月(我该怎么做?
目前,我正在遵循一种自己设计的方法,但我认为这远远不够好。这是代码。
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());
此代码返回这些值
2011年7月2日-2011年9月30日
虽然这是可以接受的,但看起来仍然不是一个完美的方式——第一次约会从月的第二天开始,而应该从第一天开始,我认为这是因为有些月29日结束,有些月30日结束。那么,我如何才能得到像2011年7月1日至2011年9月30日这样的完美日期呢。
谢谢。
var now = DateTime.Now;
var end = new DateTime(now.Year, now.Month, 1).AddDays(-1); // Last day of previous month
var start = new DateTime(now.Year, now.Month, 1).AddMonths(-3); // First day of third-last month
(你可以将new DateTime(now.Year, now.Month, 1)
存储在一个局部变量中,我想这是个人品味的问题…(
DateTime now = DateTime.Today;
DateTime firstOfMonth = now.AddDays(-now.Day + 1);
DateTime beginning = firstOfMonth.AddMonths(-3);
DateTime end = firstOfMonth.AddDays(-1);
我们通过减去(当前日期-1("回滚"到月初,周期的结束是firstOfMonth.AddDays(-1);
,周期的开始是firstOfMonth.AddMonths(-3);
var fromWithDay = DateTime.Today.AddMonths(-3);
var from = new DateTime(fromWithDay.Year, fromWithDay.Month, 1);
var toWithDay = DateTime.Today;
var to = new DateTime(toWithDay.Year, toWithDay.Month, 1).AddDays(-1);
它可能更短,但可读性较差
DateTime now = DateTime.Now;
DateTime firstDayOfThisMonth = new DateTime(now.Year, now.Month, 1);
DateTime startDate = firstDayOfThisMonth.AddMonths(-3);
DateTime endDate = firstDayOfThisMonth.AddDays(-1);
Console.WriteLine(startDate);
Console.WriteLine(endDate);