how to calculate only days between two dates in postgres sql query .

自闭症网瘾萝莉.ら 提交于 2019-12-11 06:27:13

问题


Suppose I have given two dates, if difference is one month then it should be display as 30 days.Even months also need to convert into days I have tried with age( date,now()::timestamp without time zone) but it is giving months-dates-years format. ex: 10 mons 24 days 13:57:40.5265.But I need following way. For example if two months difference is there then I need output as 60 days.


回答1:


Don't use the age() function for date/time arithmetic. It only returns "symbolic" results (which are good enough for human representation, but almost meaningless for date/time calculations; compared to the standard difference).

The standard difference operator (-) returns day-based results for both date, timestamp and timestamp with time zone (the former returns days as int, the latter two return day-based intervals):

From the day-based intervals you can extract days with the extract() function:

select current_date - '2017-01-01',
       extract(day from now()::timestamp - '2017-01-01 00:00:00'),
       extract(day from now()            - '2017-01-01 00:00:00Z');

http://rextester.com/RBTO71933




回答2:


Both of those will give that result.

select make_interval(days => ((extract(epoch from '2016-04-10'::date) - extract(epoch from '2016-02-10'::date))/(60*60*24))::integer)::text;

select format('%1$s days', ((extract(epoch from '2016-04-10'::date) - extract(epoch from '2016-02-10'::date))/(60*60*24))::integer);


来源:https://stackoverflow.com/questions/43275660/how-to-calculate-only-days-between-two-dates-in-postgres-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!