DateDiff Example

0

Please login or register to vote for this query.

(click on this box to dismiss)

Stack Overflow

Q&A for programmers

DECLARE @Birthdate AS SMALLDATETIME
DECLARE @Date AS SMALLDATETIME
DECLARE @Years AS INT
DECLARE @Years_matched AS SMALLDATETIME
DECLARE @Months AS INT
DECLARE @Months_matched AS SMALLDATETIME
DECLARE @Days AS INT

SET @Birthdate = '2012/05/31'
SET @Date = '2016/02/03'

SET @Years = DATEDIFF(yy, @Birthdate, @Date)
IF DATEPART(DY, @Birthdate) > DATEPART(DY, @Date) BEGIN
    SET @Years = @Years - 1
END
SET @Years_matched = DATEADD(yy, @Years, @Birthdate)
SET @Months = DATEDIFF(month, @Years_matched, @Date)
IF DATEPART(DAY, @Birthdate) > DATEPART(DAY, @DATE) BEGIN
  SET @Months = @Months - 1
END
SET @Months_matched = DATEADD(month, @Months, @Years_matched)
SET @Days = DATEDIFF(day, @Months_matched, @Date)

SELECT @Birthdate birthdate, @Date date,
  @Years_matched ym, @Months_matched mm,
  @Years years, @Months months, @Days days

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results