我想从今天开始在c#计算过去的半年.
在我的方案中,上半年是01/01/ -06/30。在我的方案中,下半年是07/01/ -12/31。
您将如何使用DateTime计算这个值?
例子:今天是2014年3月15日->上半年: 07/01/2013 - 12/31/2013
例子:今天是2014年7月15日,->上半年: 01/01/2014 - 06/30/2014。
谢谢!-)
发布于 2014-12-04 09:53:05
你只需看看6个月前的一个月,就可以确定其中的一半:
DateTime start, end;
var date = DateTime.Today.AddMonths(-6);
var month = date.Month;
var year = date.Year;
if (month <= 6) {
start = new DateTime(year, 1, 1);
end = new DateTime(year, 6, 30);
} else {
start = new DateTime(year, 7, 1);
end = new DateTime(year, 12, 31);
}发布于 2014-12-04 09:59:11
只要有一个if,您检查月是否大于6,并创建日期范围如下所示。
DateTime today = DateTime.Today;
if(today.Month > 6)
Console.WriteLine(new DateTime(today.Year,1,1).ToShortDateString() + "->" +
new DateTime(today.Year,6,30).ToShortDateString());
else
Console.WriteLine(new DateTime(today.Year-1,6,1).ToShortDateString() + "->" +
new DateTime(today.Year-1,12,31).ToShortDateString());发布于 2014-12-04 10:02:56
你可以这样做:
var start = new DateTime(
DateTime.Today.Year,
1 + 6 * (DateTime.Today.Month / 7),
1);
var end = new DateTime(
DateTime.Today.Year + DateTime.Today.Month / 7,
7 - 6 * (DateTime.Today.Month / 7),
1).AddDays(-1.0);https://stackoverflow.com/questions/27290743
复制相似问题