Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Months between two dates function

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??

like image 441
jobi88 Avatar asked Jan 10 '13 05:01

jobi88


People also ask

How do I calculate months between two dates in Excel?

To find the number of months or days between two dates, type into a new cell: =DATEDIF(A1,B1,”M”) for months or =DATEDIF(A1,B1,”D”) for days.

How do I display months between two dates in SQL?

Example: Oracle MONTHS_BETWEEN () function The following statement calculates the months between two specified dates: SQL> SELECT MONTHS_BETWEEN 2 (TO_DATE('02-02-2015','MM-DD-YYYY'), 3 TO_DATE('12-01-2014','MM-DD-YYYY') ) "Months" 4 FROM DUAL;.


1 Answers

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.

like image 139
araqnid Avatar answered Sep 21 '22 13:09

araqnid