PostgreSQL:两个date之间的日/月/年

我正在寻找一种方法来实现PostgreSQL中的SQLServer函数datediff。 那是,

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 

我知道我可以通过简单地使用减法来做'dd',但是对于其他两个想法呢?

尝试像这样:

 select age('2010-04-01', '2012-03-05'), date_part('year',age('2010-04-01', '2012-03-05')), date_part('month',age('2010-04-01', '2012-03-05')), date_part('day',age('2010-04-01', '2012-03-05')); 

这个function将给你两个date之间的完整的年,月,日…。 对于date变化的数量 – 我们链接,由revoua提供: http ://www.sqlines.com/postgresql/how-to/datediff

简单地减去它们:

 select '2015-01-12'::date - '2015-01-01'::date; 

这会给你:

 ?column? ---------- 11 

我花了一些时间寻找最好的答案,我想我已经拥有了。

这个SQL会给你两个date之间的天数为integer

 SELECT (EXTRACT(epoch from age('2017-6-15', now())) / 86400)::int 

..今天( 2017-3-28 )运行时,给我提供:

 ?column? ------------ 77 

对接受答案的误解:

 select age('2010-04-01', '2012-03-05'), date_part('year',age('2010-04-01', '2012-03-05')), date_part('month',age('2010-04-01', '2012-03-05')), date_part('day',age('2010-04-01', '2012-03-05')); 

..你会得到datestring的部分之间的文字差异,而不是两个date之间的时间量。

IE:

Age(interval)=-1 years -11 mons -4 days;

Years(double precision)=-1;

Months(double precision)=-11;

Days(double precision)=-4;

 SELECT date_part ('year', f) * 12 + date_part ('month', f) FROM age ('2015-06-12'::DATE, '2014-12-01'::DATE) f 

结果:6

几乎相同的function,你需要(基于atiruz的答案,缩短版本的UDF从这里 )

 CREATE OR REPLACE FUNCTION datediff(type VARCHAR, date_from DATE, date_to DATE) RETURNS INTEGER LANGUAGE plpgsql AS $$ DECLARE age INTERVAL; BEGIN age := age(date_to, date_from); CASE type WHEN 'month' THEN RETURN date_part('year', age) * 12 + date_part('month', age); WHEN 'year' THEN RETURN date_part('year', age); ELSE RETURN (date_to - date_from)::int; END CASE; END; $$; 

用法:

 /* Get months count between two dates */ SELECT datediff('month', '2015-02-14', '2016-01-03'); /* Get complete years count between two dates */ SELECT datediff('year', '2015-02-14', '2016-01-03'); /* Get days count between two dates */ SELECT datediff('day', '2015-02-14', '2016-01-03'); /* Get months count between specified and current date */ SELECT datediff('month', '2015-02-14', NOW()::date);