How to calculate age (in years) based on Date of Birth and getDate()

前端 未结 30 2438
死守一世寂寞
死守一世寂寞 2020-11-22 02:08

I have a table listing people along with their date of birth (currently a nvarchar(25))

How can I convert that to a date, and then calculate their age in years?

30条回答
  •  Happy的楠姐
    2020-11-22 02:24

    The answer marked as correct is nearer to accuracy but, it fails in following scenario - where Year of birth is Leap year and day are after February month

    declare @ReportStartDate datetime = CONVERT(datetime, '1/1/2014'),
    @DateofBirth datetime = CONVERT(datetime, '2/29/1948')
    
    FLOOR(DATEDIFF(HOUR,@DateofBirth,@ReportStartDate )/8766)
    


    OR

    FLOOR(DATEDIFF(HOUR,@DateofBirth,@ReportStartDate )/8765.82) -- Divisor is more accurate than 8766
    

    -- Following solution is giving me more accurate results.

    FLOOR(DATEDIFF(YEAR,@DateofBirth,@ReportStartDate) - (CASE WHEN DATEADD(YY,DATEDIFF(YEAR,@DateofBirth,@ReportStartDate),@DateofBirth) > @ReportStartDate THEN 1 ELSE 0 END ))
    

    It worked in almost all scenarios, considering leap year, date as 29 feb, etc.

    Please correct me if this formula have any loophole.

提交回复
热议问题