select extract(year from '2021-01-01'::timestamptz - '2020-12-31'::timestamptz); select extract(year from '2021-01-01'::timestamptz - '2020-12-31'::timestamptz); > select ('2021-01-01'::timestamptz - '2020-12-31'::timestamptz) as diff;
1 dayIt gets even strange for e.g. select DATEDIFF(year, '2021-12-01', '2022-01-01') which still returns 1 even though that's a whole month. I don't see a use case for this kind of result
So this is correct for years, right?
> select floor(extract(epoch from date_trunc('year', '2021-01-01'::timestamptz) - date_trunc('year', '2020-12-31'::timestamptz)) / 3600 / 24 / 365) as diff;
1I don't think there's a good, mathematical expression for determining something as arbitrary as dates. If there was, I don't think MS would implement a special function like DateDiff for it.
> # SELECT date_part('year', '2021-01-01'::timestamptz) - date_part('year', '2020-12-31'::timestamptz) as years;
Or what am I missing?
[edit: formatting]
If you e.g. want to check if two timestamps are more than a year apart you just compare the difference to an interval of 1 year.
I don't understand the purpose of such a calculation. If you want to check if two dates (or timestamps) fall into the same year, you compare the year part of them. If you want to check how far they are apart, you compare the difference between the two to an interval.
Semantically the code has to diff days (for example) but be aware that you crossed a year boundary (or any other).
select date_part('year','2021-01-01'::date) - date_part('year','2020-12-31'::date) as yeardiff;
yeardiff
----------
1
(1 row) extract(year from d1) - extract(year from d2)
and call it a day? select extract(month from justify_interval(timestamp '2022-01-01' - timestamp '2021-11-01'))
returns 2CREATE FUNCTION date_diff(granularity text, t1 timestamptz, t2 timestamptz) RETURNS int8 AS $$ SELECT date_part(granularity, date_trunc(granularity, t2) - date_trunc(granularity, t1))::int8 $$ LANGUAGE SQL;
I'm not sure what it's used for though
For months and days it would be a bit bigger