What is the best way to calculate the age in years from a birth date in sqlite3?
You can convert the dates to floating point numbers and subtract…
cast(strftime('%Y.%m%d', 'now') - strftime('%Y.%m%d', dob) as int)
…where dob
is a valid SQLite time string.
SELECT (strftime('%Y', 'now') - strftime('%Y', Birth_Date)) - (strftime('%m-%d', 'now') < strftime('%m-%d', Birth_Date));
This one works.
I merely ported this MySQL example: http://dev.mysql.com/doc/refman/5.0/en/date-calculations.html
Just to clarify kai's answer (it seems that editing is now very much unwelcome, and comments have a strong size limitation and formatting issues):
SELECT (strftime('%Y', 'now') - strftime('%Y', Birth_Date))
- (strftime('%m-%d', 'now') < strftime('%m-%d', Birth_Date) );
Let's assume we want full years: for the first calendar year of life, this would be zero.
For the second calendar year, this would depend on the date -- i.e. it would be:
strftime('%m-%d', 'now') >= strftime('%m-%d', Birth_Date)
["case A"]( I assume sqlite does lexicographic comparison of two date strings and returns an integer value. )
For any other calendar year, it would be the number of years between the current and the second -- i.e. strftime('%Y', 'now') - strftime('%Y', Birth_Date) - 1
, plus the same as above.
In other terms, we subtract 1 from strftime('%Y', 'now') - strftime('%Y', Birth_Date)
only if the opposite of "case A" happens -- that is, if and only if strftime('%m-%d', 'now') < strftime('%m-%d', Birth_Date)
, hence the formula.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With