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

前端 未结 30 2093
死守一世寂寞
死守一世寂寞 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条回答
  • 2020-11-22 02:32

    What about:

    DECLARE @DOB datetime
    SET @DOB='19851125'   
    SELECT Datepart(yy,convert(date,GETDATE())-@DOB)-1900
    

    Wouldn't that avoid all those rounding, truncating and ofsetting issues?

    0 讨论(0)
  • 2020-11-22 02:34
    select DATEDIFF(yy,@DATE,GETDATE()) -
    case when DATEPART(mm,GETDATE())*100+DATEPART(dd,GETDATE())>=
    DATEPART(mm,@DATE)*100+DATEPART(dd,@DATE) THEN 0
    ELSE 1 END 
    
    0 讨论(0)
  • 2020-11-22 02:36

    I believe this is similar to other ones posted here.... but this solution worked for the leap year examples 02/29/1976 to 03/01/2011 and also worked for the case for the first year.. like 07/04/2011 to 07/03/2012 which the last one posted about leap year solution did not work for that first year use case.

    SELECT FLOOR(DATEDIFF(DAY, @date1 , @date2) / 365.25)
    

    Found here.

    0 讨论(0)
  • 2020-11-22 02:36

    This will correctly handle the issues with the birthday and rounding:

    DECLARE @dob  datetime
    SET @dob='1992-01-09 00:00:00'
    
    SELECT DATEDIFF(YEAR, '0:0', getdate()-@dob)
    
    0 讨论(0)
  • 2020-11-22 02:36

    Here is how i calculate age given a birth date and current date.

    select case 
                when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date)
                    then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate()))
                else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate()))
            end as MemberAge
    go
    
    0 讨论(0)
  • 2020-11-22 02:37

    I have used this query in our production code for nearly 10 years:

    SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(Date_of_birth AS INTEGER)) / 365.25) AS Age
    
    0 讨论(0)
提交回复
热议问题