我正在编写一个计算时间跨度的程序,似乎无法正确计算数学。
我基本上要做的是计算特定日期范围是否在到达日期和结束日期之间。
(----(--------------)------) 此表示到达日期和结束日期,输入的日期范围为内括号。我基本上不关心内括号之外的日期,只是检查它们是否在外部范围内,如果这是有道理的。
但另一个问题是,如果我们的到达日期和结束日期与输入的日期范围重叠,我们在那里做什么?
我们只关心与输入日期重叠的日期。所有这些对我来说都是有意义的我只是不确定如何在代码中呈现它,下面的例子试图完成后者(虽然相当邋))是否有更有效的方法来实现这一点,实际上会产生正确的结果?
DateTime arrivalDate = new DateTime(2012,10,15);
DateTime releaseDate = new DateTime(2013,01,20);
DateTime enteredDate = new DateTime(2012,10,01);
DateTime enteredEnd = new DateTime(2012,12,31);
TimeSpan begin = TimeSpan.MinValue;
TimeSpan end = TimeSpan.MinValue;
if (arrivalDate <= enteredDate)
begin = enteredDate - arrivalDate;
else if (arrivalDate >= enteredDate)
begin = arrivalDate - enteredDate;
if (releaseDate <= enteredEnd)
end = enteredEnd - releaseDate;
else if (releaseDate >= enteredEnd)
end = releaseDate - enteredEnd;
TimeSpan total = begin + end;
TimeSpan benchmark = releaseDate - arrivalDate;
TimeSpan other = benchmark - total;
Console.WriteLine("There are " + begin.Days + " days in begin.");
Console.WriteLine("There are " + end.Days + " days in end.");
Console.WriteLine("There are " + other.Days + " days in the range.");
答案 0 :(得分:0)
确定重叠量:
DateTime arrivalDate = new DateTime(2012, 10, 15);
DateTime releaseDate = new DateTime(2013, 01, 20);
DateTime enteredDate = new DateTime(2012, 10, 01);
DateTime enteredEnd = new DateTime(2012, 12, 31);
// Whichever of { arrivalDate, enteredDate } is later
DateTime startOverlap = arrivalDate <= enteredDate ? enteredDate : arrivalDate;
// Whichever of { releaseDate, enteredEnd } is earlier
DateTime endOverlap = enteredEnd <= releaseDate ? enteredEnd : releaseDate;
TimeSpan totalOverlap = endOverlap - startOverlap;
Console.WriteLine("There are {0} days of overlap.", totalOverlap.Days);
然后确定输入的范围是否在预期范围内:
TimeSpan enteredRange = enteredEnd - enteredDate;
bool isWithinRange = enteredRange == totalOverlap;