按日期计算天数差
# select (('2019-11-18 12:05'::timestamp)::date - ('2019-10-18 12:05'::timestamp)::date) as day;
day
-----
31
# select (('2019-11-18 00:05'::timestamp)::date - ('2019-10-18 12:05'::timestamp)::date) as day;
day
-----
31
(1 row)
按时间计算天数差
# select date_part('day', '2019-11-18 12:05'::timestamp - '2019-10-18 12:05'::timestamp);
date_part
-----------
31
(1 row)
# select date_part('day', '2019-11-18 00:05'::timestamp - '2019-10-18 12:05'::timestamp);
date_part
-----------
30
(1 row)
使用age计算时间差
# select extract(day from (age('2019-11-18 12:05'::date , '2019-10-18 12:05'::date))) as day;
day
-----
0
(1 row)
# select age('2019-11-18 12:05'::date , '2019-10-18 12:05'::date);
age
-------
1 mon
(1 row)
#select age('2019-10-18 12:05'::timestamp, '2011-09-16 12:05'::timestamp);
age
----------------------
8 years 1 mon 2 days
(1 row)
postgresq age
https://www.postgresql.org/docs/12/functions-datetime.html