简体   繁体   English

日期范围重叠

[英]Ranges of dates overlapping

I have two variables containing dates. 我有两个包含日期的变量。 DateStart and DateEnd (in SQL). DateStartDateEnd (在SQL中)。
I also have two DatePicker controls (in a WinForm). 我还有两个DatePicker控件(在WinForm中)。
I import the two dates from the database and need to do something tricky. 我从数据库导入两个日期,需要做一些棘手的事情。

So the two variables create a range of dates and the two date pickers create another range of date. 因此,这两个变量创建了一系列日期,两个日期选择器创建了另一个日期范围。
How can I check if these dates range are overlapping with a Sql query ? 如何检查这些日期范围是否与Sql查询重叠?

Eg (yyyy/mm/dd format) 例如(yyyy / mm / dd格式)

DateStart = 2012/07/01 , DateEnd = 2012/07/31 DateStart = 2012/07/01 DateEnd = 2012/07/31DateEnd = 2012/07/31

| DatePicker1  | DatePicker2 | Overlapping | 
--------------------------------------------
| 2012/07/15   | 2012/07/16  |    True     |
--------------------------------------------
| 2012/07/31   | 2012/08/01  |    True     |
--------------------------------------------
| 2012/06/20   | 2012/07/01  |    True     |
--------------------------------------------
| 2012/08/01   | 2012/09/01  |    False    |
--------------------------------------------

I know it's a little messed up but I didn't know how else to ask this. 我知道这有点乱,但我不知道怎么回答这个问题。

Two date ranges overlap if start of first range is before end of second range and end of first range is after start of second range. 如果第一范围的开始在第二范围的结束之前并且第一范围的结束在第二范围的开始之后,则两个日期范围重叠。 So: 所以:

where DateStart <= @DatePicker2
  and DateEnd >= @DatePicker1

A good explanation is this way . 这样一个很好的解释

Use this function 使用此功能

/* 
 * Tests if two given periods overlap each other.
 *
 * @TS Test period start
 * @TE Test period end
 * @BS Base period start
 * @BE Base period end
 */
CREATE FUNCTION [fn_DateTime_Overlap]
(
    @TS DATETIME = NULL,
    @TE DATETIME = NULL,
    @BS DATETIME = NULL,
    @BE DATETIME = NULL
)
RETURNS BIT
AS
BEGIN
    -- More simple?
    -- return !((TS < BS && TE < BS) || (TS > BE && TE > BE));
    -- The version below, without comments 
    -- (TS >= BS && TS < BE) || (TE <= BE && TE > BS) || (TS <= BS && TE >= BE)
    IF (
        -- 1. Case:
        --       TS-------TE
        --    BS------BE
        -- TS is after BS but before BE
        (@TS >= @BS AND @TS < @BE)
        -- 2. Case
        --    TS-------TE
        --        BS---------BE
        -- TE is before BE but after BS
        OR (@TE <= @BE AND @TE > @BS)
        -- 3. Case
        --  TS----------TE
        --     BS----BE
        -- TS is before BS and TE is after BE
        OR (@TS <= @BS AND @TE >= @BE)
    ) RETURN 1
    RETURN 0
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM