PostgreSQL: days/months/years between two dates

gefei picture gefei · Jul 24, 2013 · Viewed 183.9k times · Source

I am looking for a way to implement the SQLServer-function datediff in PostgreSQL. That is,

This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate.

datediff(dd, '2010-04-01', '2012-03-05') = 704 // 704 changes of day in this interval
datediff(mm, '2010-04-01', '2012-03-05') = 23  // 23 changes of month
datediff(yy, '2010-04-01', '2012-03-05') = 2   // 2 changes of year

I know I could do 'dd' by simply using substraction, but any idea about the other two?

Answer

mehdi picture mehdi · Jun 12, 2015

Simply subtract them:

SELECT ('2015-01-12'::date - '2015-01-01'::date) AS days;

The result:

 days
------
   11