-4

Best method to check between 2 dates to see if they are within exactly 3 months of each other using T-SQL.

For example if I had these 2 dates below I want to check if @Date1 is within 3 months of @Date2 and vice versa.

 DECLARE @Date1 DATETIME = '2019-01-15 00:00:00.000'

 DECLARE @Date2 DATETIME = '2018-10-23 00:00:00.000'
gulshan arora
  • 371
  • 1
  • 8
Joe M
  • 107
  • 2
  • 2
  • 7
  • 2
    Define 3 months? 90 days? Is Feb 28 2019 three months apart from Nov 30 2018? – Salman A Aug 29 '19 at 12:30
  • 1
    Also define "within exactly 3 months". Within 3 months of each other? Exactly 3 months apart? Something else? – Eric Brandt Aug 29 '19 at 12:35
  • Unclear as the question is, I'm pretty sure the answer can be found here: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-2017 – Tab Alleman Aug 29 '19 at 12:38
  • Yes 28/02/2019 and 30/10/2018 is 3 months. Its to the exactly 3 months not 90 days i.e. 15/01/2019 & 15/10/2018 is fine but 15/01/2019 & 14/10/2018 is past. – Joe M Aug 29 '19 at 12:39

3 Answers3

1

Here is the simple statement:

SELECT abs(DATEDIFF(month, @date1, @date2)) <= 3

Sam Huang
  • 99
  • 1
  • 7
  • This is incorrect according to the explanation provided in OP. Jan 31 and Apr 1 are 3 months apart according to your answer. – Salman A Aug 29 '19 at 12:49
0

You may try this.

  DECLARE @Date1 DATETIME = '2019-01-15 00:00:00.000'

  DECLARE @Date2 DATETIME = '2018-10-23 00:00:00.000'

  SELECT dateadd(MONTH, 3,@Date1 ) >= @Date2 
DarkRob
  • 3,843
  • 1
  • 10
  • 27
0

You may try

    DECLARE @Date1 DATETIME = '2019-01-15 00:00:00.000'

    DECLARE @Date2 DATETIME = '2018-10-23 00:00:00.000'



   SELECT CASE WHEN ABS(DATEDIFF(DAY, @date1, @date2)) <= 90 THEN 'Inside 3 Months' 
ELSE 'Outside 3 months' END
Ketan Kotak
  • 942
  • 10
  • 18