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
Here's how I'd do it:
Pull the time from the database using the UNIX_TIMESTAMP() function.
The UNIX timestamp is in seconds, so add 4*60*60
to it.
Convert the modified UNIX timestamp to a date using PHP's localtime() or strftime() function.
query("SELECT UNIX_TIMESTAMP(someDatetimeColumn) ...");
. . .
$dbTimeAdjusted = localtime($row[0] + 4*60*60);
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.
You have quite a few options here:
1.
$result = mysql_query("SELECT myDate FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = strtotime("+4 hours", strtotime($myDate));
2.
// same first two lines from above
$fourHoursAhead = strtotime($myDate) + 4 * 60 * 60;
3.
$result = mysql_query("SELECT UNIX_TIMESTAMP(myDate) FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = $myDate + 4 * 60 * 60;
4.
$fourHoursAhead = strtotime("+4 hours", $myDate);
5.
$result = mysql_query("SELECT UNIX_TIMESTAMP(DATE_ADD(myDate, INTERVAL 4 HOUR))");
$fourHoursAhead = mysql_result($result, 0);
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.)
I tend to use the time() function, and this page from the manual shows them displaying the date a week in the future: http://us3.php.net/manual/en/function.time.php
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?
strtotime
has an optional second argument. Provide a Unix timestamp there and the output will be relative to that date instead of the current date.
$newTime = strtotime('+4 hours', $dbTime);
You can also use the fact that Unix timestamps are seconds-based - if you know what four hours are in seconds, you can just add that to the time integer value.