php 在 MySQL 中将秒添加到日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4055966/
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
Adding Seconds to datetime in MySQL
提问by dzm
I'm trying to add seconds to a date based on certain events that occur. Often times, if these events occur at the same time, too many seconds get added on. Here's how I am currently doing it in PHP and MySQL
我正在尝试根据发生的某些事件为日期添加秒数。很多时候,如果这些事件同时发生,就会增加太多的秒数。这是我目前在 PHP 和 MySQL 中的做法
$time_add_on = 15 - $seconds_left;
DATE_ADD(STR_TO_DATE(end_dt,'%Y-%m-%d %H:%i:%s'), INTERVAL '".$time_add_on."' SECOND
What this is doing is taking the current seconds left from the 'end_dt' subtracting 15 and adding it to the 'end_dt', basically giving you 15 seconds left.
这样做是从“end_dt”中减去当前秒数减去 15 并将其添加到“end_dt”中,基本上还剩 15 秒。
The goal here is basically too add 15 seconds or reset the date to where only 15 seconds are left. This is causing issues, where instead of resetting to 15 seconds left, it'll add 30 seconds or 45 seconds.
这里的目标基本上是增加 15 秒或将日期重置为仅剩 15 秒的位置。这会导致问题,而不是重置为剩余 15 秒,而是会增加 30 秒或 45 秒。
Would anyone know the best way to do this?
有谁知道最好的方法来做到这一点?
回答by Logan Bailey
UPDATE table end_dt = DATE_ADD(end_dt, INTERVAL 15 second)
WHERE DATE_SUB(end_dt, INTERVAL 15 second) <= NOW()
I think that's what you want, basically adds 15 seconds to end_dt when end_dt is 15 seconds away from now
我认为这就是你想要的,当 end_dt 距离现在 15 秒时,基本上为 end_dt 增加 15 秒
EDIT NEW QUERY This query should work:
编辑新查询此查询应该工作:
UPDATE `table`
SET end_dt = DATE_ADD(end_dt, INTERVAL (15 - TIMESTAMPDIFF(SECOND, NOW(), end_dt)) SECOND)
WHERE DATE_SUB(end_dt, INTERVAL 15 second) <= NOW()
回答by Amal lal T L
TIMESTAMPADD(SECOND,15,NOW())
unit = SECOND seconds to add = 15
单位 = 添加秒数 = 15