简体   繁体   English

在PostgreSQL中使用INTERVAL添加小时日期/时间

[英]Using INTERVAL in PostgreSQL to add hours date/time

Here is the code in PostgreSQL I am trying to run: 这是我尝试运行的PostgreSQL中的代码:

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 2010-11-19 01:11:22

PostgreSQL error code is this: PostgreSQL错误代码是这样的:

ERROR: syntax error at or near "4" 错误:语法错误在“ 4”或附近

it is referring to the '4' in the line 'INTERVAL 4 HOUR'. 它是指“间隔4小时”行中的“ 4”。

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. 我需要将时间/时间戳(与上述格式完全相同)与存储的时间/日期加上4小时进行比较。 So the desired end result is to return: '2010-11-19 05:11:22' . 因此,所需的最终结果是返回: '2010-11-19 05:11:22'

If this can be done in PHP or directly in SQL? 是否可以用PHP或直接用SQL完成?

Based on your comment 根据您的评论

I am just typing these codes into PgAdmin. 我只是在PgAdmin中输入这些代码

It looks like you're actually using PostgreSQL not MySQL. 看起来您实际上是在使用PostgreSQL而不是MySQL。

You can view your existing code running on PostgreSQL in action on PostgreSQL here which gives the same error as you get above. 您可以在此处查看在PostgreSQL上运行的现有代码在PostgreSQL上的运行情况,它给出与上述相同的错误。

To correctly work with dates in PostgreSQL, you can view a list of date functions on the PostgreSQL documentation site here 要在PostgreSQL中正确使用日期,可以在PostgreSQL 文档站点上查看日期函数列表。

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: 我找到了一种适用于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. 现在,我可以将其重新插入SQL。

Thanks! 谢谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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