计算日期的逻辑正确,但代码不正确



我正在编写一个计算时间跨度的程序,但似乎无法正确计算。

我主要想做的是计算一个特定的日期范围是否在到达日期和结束日期之间。

(------)这个表示到达日期和结束日期,输入的日期范围作为内括号。我基本上不在乎内括号外的日期,只是检查一下它们是否在外括号内,如果这有意义的话。

但另一个问题出现了,如果我们的到达和结束日期与输入的日期范围重叠,我们该怎么办?

我们只关心与输入日期重叠的日期。所有这些对我来说都是有意义的——我只是不确定如何在代码中表示它,下面的例子试图实现后者(尽管相当草率)——是否有一种更有效的方法可以真正产生正确的结果?

        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.");         

要确定重叠量:

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;

相关内容

  • 没有找到相关文章

最新更新