简体   繁体   中英

Using INTERVAL in PostgreSQL to add hours date/time

Here is the code in PostgreSQL I am trying to run:

select DATE_ADD(whenbooked,INTERVAL 4 HOUR) from booking WHERE id = 12310;

OR I try to run this code:

select DATE_ADD('2010-11-19 01:11:22',INTERVAL 4 HOUR)

Both codes access date/time stored in the same manner:

2010-11-19 01:11:22

PostgreSQL error code is this:

ERROR: syntax error at or near "4"

it is referring to the '4' in the line 'INTERVAL 4 HOUR'.

I can't figure out what the issue is.

I need to compare a time/stamp (written in exactly the same format as above) with the stored time/date PLUS 4 hours. So the desired end result is to return: '2010-11-19 05:11:22' .

If this can be done in PHP or directly in SQL?

Based on your comment

I am just typing these codes into PgAdmin.

It looks like you're actually using PostgreSQL not MySQL.

You can view your existing code running on PostgreSQL in action on PostgreSQL here which gives the same error as you get above.

To correctly work with dates in PostgreSQL, you can view a list of date functions on the PostgreSQL documentation site here

What you're trying to do is this:

SELECT TIMESTAMP '2010-11-19 01:11:22' + INTERVAL '4 HOURS';

I found a method that works for me in PHP:

$desiredEndTime = strtotime("2010-11-19 01:11:22 + 10 hours");
echo date("Y-m-d H:i:s", $desiredendtime);

Looks like it converts the date/time into a weird-looking integer. And then on the second line it converts it back into my desired format. Now I can just insert that back into SQL.

Thanks!

使用“ strtotime”方法将其简单地转换为时间戳,然后您可以执行任何操作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM