Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate Age/Number of Years between two dates [duplicate]

Possible Duplicate:
How to calculate age in T-SQL with years, months, and days

On a project I was working on, I was required to calculate a persons age when they join the system; after looking on the internet I found various ways this could be done, but most of them had slight issues when it involved a Leap-Year.

The solution below is how I calculate number of years past / age. Hope this helps others

like image 285
ccStars Avatar asked Dec 28 '12 15:12

ccStars


3 Answers

You need to add the following method to your database:

CREATE FUNCTION [dbo].[fnCalAge] (@DiffFrom DATE, @DiffTo DATE) RETURNS INT
AS
BEGIN
    DECLARE @NumOfYears INT
    SET @NumOfYears = (SELECT 
                         DATEDIFF(YEAR, @DiffFrom, @DiffTo) + 
                         CASE 
                           WHEN MONTH(@DiffTo) < MONTH(@DiffFrom) THEN -1 
                           WHEN MONTH(@DiffTo) > MONTH(@DiffFrom) THEN 0 
                           ELSE 
                             CASE WHEN DAY(@DiffTo) < DAY(@DiffFrom) THEN -1 ELSE 0 END 
                         END)
    IF @NumOfYears < 0
    BEGIN
        SET @NumOfYears = 0;
    END

    RETURN @NumOfYears;
END

You then call it in your SQL Query, similar to the following:

SET DATEFORMAT dmy 

SELECT dbo.fnCalAge(CAST('20/06/1987' AS DATE), CAST('20/06/2013' AS DATE))
like image 51
ccStars Avatar answered Sep 26 '22 14:09

ccStars


assuming @bDate is datetime of birthdate and @today is todays date, then...

 Declare @bDay Date = '31 dec 2000'
 Declare @today Date = cast(getdate() as date)
 Select datediff(Year, @bDay, @today) - 
        case When datepart(dayofYear, @today) <
                  datepart(dayofYear, @bDay) Then 1 Else 0 End
like image 26
Charles Bretana Avatar answered Sep 22 '22 14:09

Charles Bretana


Replace hiredate with DOB for age. Replace sysdate with your date such as to_date('28-DEC-2012') :

SELECT empno, ename, hiredate, TRUNC(MONTHS_BETWEEN(sysdate, hiredate)/12)  years_of_service 
 FROM scott.emp
/
like image 36
Art Avatar answered Sep 22 '22 14:09

Art