I\'m having a problem here..
Supposed I have this kind of datetime.
$date = strtotime($date);
I need this to be converted into t
Nobody offered a DateTime
object solution yet, so I will.
It is the most modern method for handling datetime and doesn't require any calculation of minutes & seconds.
I always like to drop in some sort of timezone declaration to make things definitive. Daylight Saving Time is normally a concern with datetime manipulations, but probably okay in this case. Feel free to modify the timezone for your case.
PHP manual links:
Code (including formatted time for comparison) Demo Link:
$now=new DateTime('NOW UTC');
$now_stamp=$now->getTimestamp();
$formatted_now=$now->format("Y-m-d H:i:s");
echo "$now_stamp ($formatted_now)\n";
$hour_ago=$now->modify('-1 hour');
$hour_ago_stamp=$hour_ago->getTimestamp();
$formatted_hour_ago=$hour_ago->format("Y-m-d H:i:s");
echo "$hour_ago_stamp ($formatted_hour_ago)";
Output:
1492687193 (2017-04-20 11:19:53)
1492683593 (2017-04-20 10:19:53)
strtotime will give you the unix timestamp of your date. From this timestamp, you then subtract your hour:
$date = strtotime($date) - 3600; // 3600 = 60 * 60
If you call strtotime($date - 3600)
, it's like obtaining the time for -3600 (e.g. strtotime(-3600)
) which makes no sense because strtotime expects a string as first argument.
86400 seconds is one DAY, not one hour.
The output of strtotime() is a unix timestamp. 3600 seconds earlier is that timestamp minus one hour. So:
$date = strtotime($somestring);
$hourago = $date - 3600;
Or, depending on the original format of $somestring:
$hourago = strtotime($somestring . " - 1 hour");
And don't forget about date_default_timezone_set()
Try this query
$query= "insert into yourTable(otherValues, date)
values (otherFields, DATE_ADD(NOW(),INTERVAL -1 hour))
Use DATE_ADD to insert a date value which is 1 hour less than current time.
You could do:
$testDateStr = strtotime($date);
$finalDate = date("Y-m-d H:i:s", strtotime("-1 hour", $testDateStr));
Hope it helps