在Postgres中添加current_timestamp和days列的总和

时间:2009-05-08 06:32:15

标签: postgresql timestamp

我希望通过将天数添加到当前时间来更新列。在pseudosyntax中它将是:

UPDATE foo
SET time = current_timestamp + days::integer

天是同一张表中的一列。

3 个答案:

答案 0 :(得分: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);

现在这可行:

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

注意:

由于某种原因,在Postgres中内置了一个到目前为止的整数,这可以工作:

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

这不会(除非你定义自己的运算符,见上文):

select current_timestamp + 3

答案 1 :(得分:5)

select now() + cast('1 day' as interval) * 3 -- example: 3 days

答案 2 :(得分:1)

没有时区的calculatedDate时间戳;

calculatedDate := current_timestamp + interval '1' day * days_count;