Home > Net >  How do I get the date of birth from a full age in postgresql?
How do I get the date of birth from a full age in postgresql?

Time:09-26

I have an age on the format 57 years 5 months 7 days, and I want to deduct the date of birth from it in postgresql on a format like yyyy-mm-dd, how do I do that?

CodePudding user response:

We can get the past date using multiple intervals. I added a couple examples to the data to check that it's working.

select  *
       ,current_date   (interval '-1 years'*years)   (interval '-1 month'*months)   (interval '-1 day'*days) as dte
from    t
years months days dte
57 5 7 1965-04-18 00:00:00
36 11 12 1985-10-13 00:00:00
6 2 1 2016-07-24 00:00:00

Fiddle

CodePudding user response:

Here's a way with concat_ws

   select *, current_date - concat_ws (' ', years, 'years', months, 'months', days, 'days')::interval as dte
    from   t

Here's a way with make_interval

select *, current_date - make_interval(years, months, 0, days) as dte
from   t

Here's a way with format

select *, current_date - format('%s years %s months %s days', years, months, days)::interval as dte
from   t
years months days dte
57 5 7 1965-04-18 00:00:00
36 11 12 1985-10-13 00:00:00
6 2 1 2016-07-24 00:00:00

Fiddle

  • Related