Difference in postgresql date months

Asked

Viewed 6,508 times

7

I need to catch the difference of two months dates, for example 16/03/2013 until the date 16/07/2014. If I do

select extract('Month' from age(data1, data2))

What will return is a result 4, as it informs that the difference between the date is 1 year of 4 months.

But what I need is total in months, 15 months apart. There is some way?

3 answers

7

  • I actually had a problem with the date, the month if I have using last year’s negative date. For example, (DATE_PART('month', now()) - DATE_PART('month', '12/12/2013':timestamp)).

  • Which is the expected result? 12/2013 for 08/2014. First account = 1 ano = 12 meses. Second account: August to December = 8 - 12 = -4 meses. of 12/2013 until 08/2014 = 12 - 4 = 8 meses.

  • Anyway, if you always want absolute values you can use the function abs(x) or ensure that the longest date is always used as data2 in his select. Otherwise you will have cases like 12/2013 - 08/2014 whose result will return, correctly, -8 months.

7


Exists in Postgresql a Function Age which in my view portrays well the difference between dates. SQL below also demonstrates the result of months difference between two dates:

SELECT ((ANOS * 12) + MESES) AS MESES
FROM 
(
  SELECT 
    CAST(TO_CHAR(AGE(data2, data1),'YY') AS INTEGER) AS ANOS,
    CAST(TO_CHAR(AGE(data2, data1),'MM') AS INTEGER) AS MESES, 
    CAST(TO_CHAR(AGE(data2, data1),'DD') AS INTEGER) AS DIAS
  FROM tabela
) AS tabela

Sqlfiddle

  • 1

    I just wanted to understand the negative vote, I had +1 and it was withdrawn for what reason?

2

If it is necessary only the whole number of months:

select
    (
        select count(*) - 1
        from generate_series(date1, date2, '1 month')
    ) as meses
from (values
    ('2013-03-16'::date, '2014-07-16'::date)
) g (date1, date2)
;
 meses 
-------
    16

Browser other questions tagged

You are not signed in. Login or sign up in order to post.