Reputation: 2825
$time1 = time();
$time2 = mktime(date('H')+1, date('i'), date('s'), date('m'), date('d'), date('Y'));
$diff = $time2 - $time1
echo date('Y/m/d H:i:s', $time)."<br/>";
echo date('Y/m/d H:i:s', $new_time)."<br/>";
echo date('H', $diff);
Output:
2013/09/03 09:25:52
2013/09/03 10:25:52
02 //which should be 1
Why is the $diff always different from the correct answer by 1?
Upvotes: 0
Views: 71
Reputation: 34125
The second parameter of date()
expects a timestamp, you're giving it the difference of two timestamps - in this case 3600. var_dump(date("Y-m-d H:i:s", 3600));
is "1970-01-01 02:00:00".
Look into the DateTime
and DateInterval
classes. Your code's equivalent looks like this:
$time1 = new \DateTime();
$time2 = (new \DateTime())->modify("+1 hour");
$diff = $time1->diff($time2, true);
var_dump($diff->h); // int(1)
Upvotes: 1
Reputation: 10717
You getting only seconds between times. Try divide to 3600
echo round($diff/3600); // 1
Upvotes: 0