我想计算今天从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。
提前致谢! ; - )
答案 0 :(得分:7)
您只需要查看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);
}
答案 1 :(得分:1)
如果你检查月份是否大于6,只需要一个if else,并创建如下的日期范围。
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());
答案 2 :(得分:1)
你可以这样做:
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);
答案 3 :(得分:0)
退一天,直到你遇到第12个月或第06个月
// get first of this month
DateTime prev = new DAteTime( DateTime.Today.Year, DateTime.Today.Month, 1);
bool found = false;
while(found == false){
prev = prev.AddDays(-1);
if(prev.Month == 12)
found = true;
if(prev.Month == 6)
found = true
}
// then when found, count back 6 months from that
DateTime start = prev.AddMonths(-6)
// then get the first of that month
start = new DateTime(start.Year, start.Month, 1);
答案 4 :(得分:0)
请找到以下代码段。
string firstHalf = "30/06/";
int currentYear = DateTime.Now.Date.Year;
if (DateTime.Now.Date > Convert.ToDateTime(firstHalf + Convert.ToString(currentYear)).Date)
{
MessageBox.Show("Last Half Year : " + "01/01/" + Convert.ToString(currentYear) + " to 30/06/" + Convert.ToString(currentYear));
}
else
MessageBox.Show("Last Half Year : " + "01/07/" + Convert.ToString(currentYear - 1) + " to 31/12/" + Convert.ToString(currentYear - 1));
答案 5 :(得分:0)
谢谢你们。我更喜欢GvS的答案。
我这样做:
var halfyear = (float)DateTime.Today.Month / 6;
var halfyearModulo = halfyear % 1;
if (halfyearModulo == 0)
halfyear--;
var minimumDate = new DateTime(DateTime.Today.Year, ((int)halfyear * 6) + 1, 1).AddMonths(-6);
var maximumDate = minimumDate.AddMonths(6);
但我认为GvSs更好。