5

I want update a column by adding days to current time. In pseudosyntax it would be:

UPDATE foo
SET time = current_timestamp + days::integer

days is a column in the same table.

egaga
  • 21,042
  • 10
  • 46
  • 60

3 Answers3

8
select now() + cast('1 day' as interval) * 3 -- example: 3 days
Michael Buen
  • 38,643
  • 9
  • 94
  • 118
  • This was the actually exactly what I needed. I am not sure why this isn't part of your answer @Michael Buen – QuirkyBit Jan 26 '21 at 00:00
6
create function add_days_to_timestamp(t timestamptz, d int) 
returns timestamptz
as
$$
begin
    return t + interval '1' day * d;
end; 
$$ language 'plpgsql';


create operator + (leftarg = timestamptz, rightarg = int, 
         procedure = add_days_to_timestamp);

Now this would work:

update foo set time = current_timestamp + 3 /* day variable here, 
or a column from your table */

Note:

for some reason, adding an integer to date is built-in in Postgres, this would work:

select current_timestamp::date + 3 -- but only a date

this would not(unless you define your own operator, see above):

select current_timestamp + 3
Michael Buen
  • 38,643
  • 9
  • 94
  • 118
2

calculatedDate timestamp without time zone;

calculatedDate := current_timestamp + interval '1' day * days_count; 
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
Ankur Srivastava
  • 855
  • 9
  • 10