检查2个日期之间的日期时间

时间:2014-07-30 19:56:24

标签: c# date c#-4.0

我必须检查此日期之间的日期时间。我有2个旧日期和2个新日期,基本上需要检查它是否匹配。

DateTime old_start_Dt = Convert.ToDateTime("07/28/2014 3:30:00 AM");
DateTime old_end_Dt = Convert.ToDateTime("07/28/2014 4:00:00 AM");

DateTime new_start_Dt = Convert.ToDateTime("07/28/2014 3:45:00 AM");
DateTime new_end_Dt = Convert.ToDateTime("07/28/2014 5:00:00 AM");

//above dates example should found match.

bool _matchfound = false;

if ((new_start_Dt >= old_start_Dt || new_start_Dt <= old_start_Dt)
   && (new_end_Dt >= old_end_Dt || new_end_Dt <= old_end_Dt))
{
    _matchfound = true;
}

在我的逻辑中猜测我错了什么?

1 个答案:

答案 0 :(得分:1)

看起来你的if陈述永远是真的。考虑一下你正在测试

new >= old || new <= old

嗯,其中一个无论如何都是真的。因此,无论您的日期具有什么值,if语句的两个部分都将为真。

我不确定您的具体用途,但如果您想测试新范围是否在旧范围内,这应该可行:

if (new_start_Dt >= old_start_Dt && // new starts after old starts
    new_start_Dt < old_end_Dt &&    // new starts before old ends
    new_end_Dt > old_start_Dt &&    // new ends after old starts
    new_end_Dt <= old_end_Dt &&     // new ends before old ends
    old_start_Dt < old_end_Dt &&    // old start is before old end
    new_start_Dt <= new_end_Dt &&)  // new start is before new end
{
    ...
}