Reputation: 67
Is there a function on postgresql that will let me get the current datetime for the past year or x number of past years?
I know i can do this select now() - interval '1 year';
but in a function how can i put the number of years in a variable
x := '2 year'
Is it possible to do this select now() - interval x;
I tried but it give me error
Upvotes: 3
Views: 383
Reputation: 894
If you want to use variable you can do this:
CREATE OR REPLACE FUNCTION func(input integer)
RETURNS TIMESTAMP WITHOUT TIME ZONE AS
$BODY$
declare
result TIMESTAMP WITHOUT TIME ZONE;
begin
select now() - (input || ' years')::interval into result;
return result;
end;
$BODY$
LANGUAGE plpgsql VOLATILE
Upvotes: 4
Reputation: 1269593
For the date, you would use:
select current_date - interval '1 year'
For the date/time:
select now() - interval '1 year'
Upvotes: 2