SQLite: How to calculate age from birth date

后端 未结 8 1833
独厮守ぢ
独厮守ぢ 2020-12-16 15:00

What is the best way to calculate the age in years from a birth date in sqlite3?

8条回答
  •  眼角桃花
    2020-12-16 15:33

    To get @Bruno Costa's answer to work I had to add brackets around the strftime difference calculation on the 4th line and reverse the comparison to 'now' to be less than or equal: as I understand it the calculation is working out whether the calculated date is before or after today. If the calculated date is today or earlier then the birthday has already been this year or is today:

    select
        case
            when date(dob, '+' ||
                (strftime('%Y', 'now') - strftime('%Y', dob)) ||
                ' years') <= date('now')
            then strftime('%Y', 'now') - strftime('%Y', dob)
            else strftime('%Y', 'now') - strftime('%Y', dob) - 1
        end
        as age
    from t;
    

    Note that the solution linked to in @Bruno Costa's answer was untested.

提交回复
热议问题