将 30 分钟添加到日期时间 php/mysql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1436827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:34:04  来源:igfitidea点击:

adding 30 minutes to datetime php/mysql

phpmysqldatetimestrtotime

提问by someisaac

I have a datetime field (endTime) in mysql. I use gmdate() to populate this endTime field.

我在 mysql 中有一个日期时间字段(endTime)。我使用 gmdate() 来填充这个 endTime 字段。

The value stored is something like 2009-09-17 04:10:48. I want to add 30 minutes to this endtime and compare it with current time. ie) the user is allowed to do a certain task only 30 minutes within his endTime. After 30 minutes of his endTime, i should not allow him to do a task.

存储的值类似于 2009-09-17 04:10:48。我想为此结束时间添加 30 分钟,并将其与当前时间进行比较。即)用户只允许在他的 endTime 内的 30 分钟内完成某项任务。在他结束时间 30 分钟后,我不应该让他做任务。

how can i do that in php?

我怎么能在 php 中做到这一点?

i'm using gmdate to make sure there are no zone differences.

我正在使用 gmdate 来确保没有区域差异。

Thanks in advance

提前致谢

回答by RageZ

If you are using MySQLyou can do it like this:

如果你使用MySQL,你可以这样做:

SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;


For a pure PHP solution use strtotime


对于纯 PHP 解决方案,请使用strtotime

strtotime('+ 30 minute',$yourdate);

回答by Cem Kalyoncu

Try this one

试试这个

DATE_ADD(datefield, INTERVAL 30 MINUTE)

回答by staticsan

Dominc has the right idea, but put the calculation on the other side of the expression.

Dominc 有正确的想法,但将计算放在表达式的另一侧。

SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)

This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.

这样做的好处是您只需进行一次 30 分钟的计算,而不是对每一行进行计算。这也意味着 MySQL 可以使用该列上的索引。这两者都可以为您提供加速。

回答by Dominic Rodger

MySQL has a function called ADDTIMEfor adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).

MySQL 有一个函数可以调用ADDTIME两次相加 - 因此您可以在 MySQL 中完成所有操作(前提是您使用的是 >= MySQL 4.1.3)。

Something like (untested):

类似的东西(未经测试):

SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')

回答by Basant Rules

Use DATE_ADD function

使用 DATE_ADD 函数

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);