Skip to content

Instantly share code, notes, and snippets.

@wgzhao
Created August 15, 2012 06:51
Show Gist options
  • Save wgzhao/3357205 to your computer and use it in GitHub Desktop.
Save wgzhao/3357205 to your computer and use it in GitHub Desktop.
create simple date diff function ,can return the number of years/months/days between two date
--
create or replace function datediff(m text,d1 date,d2 date) returns int as $$
declare
d1_year int;
d1_month int;
d2_year int;
d2_month int;
day int;
begin
select extract(year from d1) into d1_year;
select extract(month from d1) into d1_month;
select extract(year from d2) into d2_year;
select extract(month from d2) into d2_month;
if m = 'year' then
return (d2_year - d1_year);
elsif m = 'month' then
return (d2_year - d1_year) * 12 + (d2_month - d1_month);
elsif m = 'day' then
select d2 - d1 into day;
return day;
end if;
end;
$$ language plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment