What is the best way to calculate the age in years from a birth date in sqlite3?
I have spent whole my Weekend on this Topic and created this Query.
SELECT ID,
Name,
InitialDate,
LastDate,
CASE
WHEN strftime('%m', LastDate) > strftime('%m', InitialDate) THEN strftime('%Y', LastDate) - strftime('%Y', InitialDate)
WHEN strftime('%m', LastDate) < strftime('%m', InitialDate) THEN strftime('%Y', LastDate) - strftime('%Y', InitialDate) - 1
WHEN strftime('%m', LastDate) = strftime('%m', InitialDate) THEN
CASE
WHEN strftime('%d', LastDate) >= strftime('%d', InitialDate) THEN strftime('%Y', LastDate) - strftime('%Y', InitialDate)
ELSE strftime('%Y', LastDate) - strftime('%Y', InitialDate) - 1
END
END AS Years,
CASE
WHEN strftime('%m', LastDate) == strftime('%m', InitialDate) THEN
CASE
WHEN strftime('%d', LastDate) == strftime('%d', InitialDate) THEN ( strftime('%m', LastDate) - strftime('%m', InitialDate) ) -- i.e., 0
WHEN strftime('%d', LastDate) > strftime('%d', InitialDate) THEN ( strftime('%m', LastDate) - strftime('%m', InitialDate) ) -- i.e., 12
WHEN strftime('%d', InitialDate) > strftime('%d', LastDate) THEN (strftime('%m', LastDate) - strftime('%m', InitialDate)) + 11 -- i.e., 11
END
WHEN strftime('%m', LastDate) > strftime('%m', InitialDate) THEN
CASE
WHEN strftime('%d', LastDate) == strftime('%d', InitialDate) THEN strftime('%m', LastDate) - strftime('%m', InitialDate)
WHEN strftime('%d', LastDate) > strftime('%d', InitialDate) THEN strftime('%m', LastDate) - strftime('%m', InitialDate)
WHEN strftime('%d', InitialDate) > strftime('%d', LastDate) THEN ( strftime('%m', LastDate) - strftime('%m', InitialDate) ) - 1
END
WHEN strftime('%m', InitialDate) > strftime('%m', LastDate) THEN
CASE
WHEN strftime('%d', LastDate) == strftime('%d', InitialDate) THEN 12 - ( strftime('%m', InitialDate) - strftime('%m', LastDate) )
WHEN strftime('%d', LastDate) > strftime('%d', InitialDate) THEN 12 - ( strftime('%m', InitialDate) - strftime('%m', LastDate) )
WHEN strftime('%d', InitialDate) > strftime('%d', LastDate) THEN 11 - (strftime('%m', InitialDate) - strftime('%m', LastDate))
END
END AS Months,
CASE
WHEN strftime('%d', LastDate) == strftime('%d', InitialDate) THEN 0
WHEN strftime('%d', LastDate) > strftime('%d', InitialDate) THEN strftime('%d', LastDate) - strftime('%d', InitialDate)
WHEN strftime('%d', InitialDate) > strftime('%d', LastDate) THEN ( strftime('%d', date(InitialDate, 'start of month', '+1 month', '-1 day') ) - strftime('%d', InitialDate) + strftime('%d', LastDate) )
END AS Days
FROM tbl_Dates;
Tested on a Data Set consist of 248 Records. Years and Months are with calculated 100% Accuracy. While Days are 124 out of 248 Records are with Difference of ±1 Day(s). I would request other Genius Minds to Dig out and find the remaining solution. For me Its OK and working 100% Fine.