SDU Tools: Calculate Age in Months

SDU Tools: Calculate Age in Months

Another request that I received a while back, for a new function in our free SDU Tools for developers and DBAs, was to be able to find someone’s age in months. The same would apply to anything where the distance between two dates needs to be measured in months. In response, we added a new function CalculateAgeInMonths.

It takes two parameters:

@StartingDate date - the date to calculate from (could be a birth date if it’s an age) @CalculationDate date - the date to calculate the age to

The function returns an integer number of months.

Find out more

You can see it in action in the main image above, and in the video here. The full current version of the code is also shown below:

YouTube Video

You can use our tools as a set or as a great example of how to write functions like these.

Access to SDU Tools is one of the benefits of being an SDU Insider, along with access to our other free tools and eBooks. Please just visit here for more info:

http://sdutools.sqldownunder.com

Latest version of the code

Note: the code might wrap when displayed below.

CREATE FUNCTION SDU_Tools.CalculateAgeInMonths
(
    @StartingDate date,
    @CalculationDate date
)
RETURNS int
AS
BEGIN

-- Function:      Return an age in months from a starting date to a calculation date
-- Parameters:    @StartingDate date -> when the calculation begins 
-- @CalculationDate date -> when the age is calculated to 
-- Action:        Return an age in months from a starting date to a calculation date 
-- Return:        int  
-- Refer to this video: https://youtu.be/AZaEfnIqt_E
--
-- Test examples: 
/*

SELECT SDU_Tools.CalculateAgeInMonths('1968-11-20', SYSDATETIME());
SELECT SDU_Tools.CalculateAgeInMonths('20210901', '20211213');

*/
    RETURN (YEAR(@CalculationDate) - YEAR(@StartingDate)) * 12 
           + MONTH(@CalculationDate) - MONTH(@StartingDate) 
           + IIF(DAY(@CalculationDate) < DAY(@StartingDate), -1, 0);
END;

2025-02-02