Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add minutes to CURRENT_TIMESTAMP in PostgreSQL

Tags:

postgresql

I have a procedure in PostgreSQL that I want to add the number of minutes to CURRENT_TIMESTAMP like below

timestamp_var := CURRENT_TIMESTAMP + interval '20 minutes';

But the number of minutes is a parameter.

Do we have the functions to do this?

Pls help me in this case

CREATE OR REPLACE FUNCTION modify_time(id users.id%TYPE, min integer) AS $$  BEGIN UPDATE         users     SET         modified_at = CURRENT_TIMESTAMP     WHERE         user_id = id; END $$ LANGUAGE plpgsql; 

I want to add min minutes to CURRENT_TIMESTAMP thanks

like image 713
OneCart Avatar asked Feb 13 '14 04:02

OneCart


People also ask

Does Dateadd work in PostgreSQL?

Although PostgreSQL does not provide DATEADD function similar to SQL Server, Sybase or MySQL, you can use datetime arithmetic with interval literals to get the same results.

What is Current_timestamp in PostgreSQL?

The PostgreSQL CURRENT_TIMESTAMP() function returns the current date and time with time zone. It is important to note that the time and time zone returned by this function is from the time the transactions start.

Does Postgres support timestamp?

PostgreSQL supports the full set of SQL date and time types, shown in Table 8.9.


2 Answers

You can multiply intervals by integers. The following gives you a timestamp 20 minutes in the future:

select current_timestamp + (20 * interval '1 minute') 

Or, as murison mentions in another answer to this question, there is a more succinct way to express this:

select current_timestamp + (20 ||' minutes')::interval 

So, your code could look like:

CREATE OR REPLACE FUNCTION modify_time(id users.id%TYPE, min integer) AS $$  BEGIN UPDATE         users     SET         modified_at = CURRENT_TIMESTAMP + (min * interval '1 minute')     WHERE         user_id = id; END $$ LANGUAGE plpgsql; 
like image 107
stvsmth Avatar answered Sep 18 '22 15:09

stvsmth


the other way is

select current_timestamp + (20 ||' minutes')::interval 
like image 32
murison Avatar answered Sep 20 '22 15:09

murison