Bing Bing - 6 months ago 28
PHP Question

PHP Why does strtotime give me the wrong day using YYYY-MM-DD HH:MM:SS +15 hours?

When I call

strtotime("2016-05-06 15:00:00 +15.98 hours")
I'd expect
2016-05-07 06:58:48
but instead I get
2016-05-10 02:00:00
. What gives?

You can test here yourself:


  1. Use strtotime: http://php.fnlist.com/date_time/strtotime

  2. Convert output int to timestamp: http://www.epochconverter.com/


Answer

Try this instead:

//60 * 60 * 15.98 = 57,528 seconds
$add = round(60 * 60 * 15.98);

$timestamp = strtotime("2016-05-06 15:00:00") + $add;

$dt = date("Y-m-d H:i:s", $timestamp);

echo $dt; //2016-05-07 06:58:48

This will calculate to 2016-05-07 06:58:48

As for why it incorrectly added the 15.98 hours is more complex. There has been a reported bug for this problem and currently floats aren't supported in date formatting in PHP. Since you can not directly use floats in date formatting, you must substitute something like "1.5 years" with "18 months", or do arithmetic before and round it like this:

//60 * 60 * 15.98 = 57,528 seconds
$timeToAdd = round(60 * 60 * 15.98);

And then call strtotime() like in the above example

$date = strtotime("2016-05-06 15:00:00") + $timeToAdd;