Months between two dates function

jobi88 picture jobi88 · Jan 10, 2013 · Viewed 13.8k times · Source

In oracle i can find out no:of months between using MONTHS_BETWEEN function.

In postgres i am using extract function for this. eg.like

select 
    extract(year from age(current_date, '2012-12-09')) * 12
    + 
    extract(month from age(current_date, '2012-12-09'))

Is there any other ways(built in functions) in postgres??

Answer

araqnid picture araqnid · Jan 10, 2013

This is easy to re-implement in PostgreSQL just using SQL functions to tidy up what you've already got:

create function months_of(interval)
 returns int strict immutable language sql as $$
  select extract(years from $1)::int * 12 + extract(month from $1)::int
$$;

create function months_between(date, date)
 returns int strict immutable language sql as $$
   select abs(months_of(age($1, $2)))
$$;

And now select months_between('1978-06-20', '2011-12-09') produces 401.