Adding time in PHP

2020-02-16 04:25发布

I am pulling a datetime from a mysql db and i would like to add X hours to it then compare it to the current time. So far i got

$dateNow = strtotime(date('Y-m-d H:i:s'));
$dbTime = strtotime($row[0]);

then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?

NOTE: I am using php 5.1.2 so date_add doesnt work (5.3.0)

8条回答
看我几分像从前
2楼-- · 2020-02-16 04:53

strtotime("+4 hours", $dbTime);

The second argument is the timestamp which is used as a base for the calculation of relative dates; it defaults to the current time. Check out the documentation.

Edit: For short periods of time, max 1 week, adding seconds to a timestamp is perfectly acceptable. There is always (7 * 24 * 3600) seconds in a week; the same cannot be said for a month or year. Furthermore, a unix timestamp is just the number of seconds that have elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT). That is not effected by timezones or daylight-savings. Timezones and daylight-savings are only important when converting a unix timestamp to an actual calendar day and time.

查看更多
ら.Afraid
3楼-- · 2020-02-16 04:53

Probably the safest way to do the compare is right in the SQL

SELECT * FROM my_table WHERE someDateTimeColumn < DATE_ADD(NOW(), INTERVAL 4 hour)

And since you're assembling it in PHP, you can dynamically replace the "4 hour" bit with whatever your code needs to compare.

(Note: putting the entire calculation on the other side of the comparison to the column allows MySQL to do the calculation once per query, rather than once per row, and also use the table's index, if that column has one.)

查看更多
登录 后发表回答