AlexZheda
AlexZheda

Reputation: 475

Extracting number of months from an interval

What am I doing wrong?

SELECT DATE_PART('month', '2018-05-31'::timestamp - '2018-02-24'::timestamp);

It returns 0! All the time. Why?

I am on PostgreSQL 10.4.

Upvotes: 0

Views: 459

Answers (2)

Laurenz Albe
Laurenz Albe

Reputation: 246578

Vao Tsun has explained why.

One good solution for you might be to use the age function, which formats the interval in years, months and days:

SELECT date_part('month', age('2018-05-31'::timestamp, '2018-02-24'::timestamp));

 date_part 
-----------
         3
(1 row)

That will return more accurate results, because it does not have to assume that every month has 30 days.

Upvotes: 3

Vao Tsun
Vao Tsun

Reputation: 51511

you have:

t=# select '2018-05-31'::timestamp - '2018-02-24'::timestamp;
 ?column?
----------
 96 days
(1 row)

so:

t=# SELECT DATE_PART('day', '2018-05-31'::timestamp - '2018-02-24');
 date_part
-----------
        96
(1 row)

try:

t=# SELECT DATE_PART('month', justify_interval('2018-05-31'::timestamp - '2018-02-24'::timestamp));
 date_part
-----------
         3
(1 row)

I think the need of justifying interval prior to using it with date_part should be noted at
https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT, to be clear - true...

Upvotes: 3

Related Questions