php strtotime in seconds and minutes

DouzeBri DouzeBra picture DouzeBri DouzeBra · Jun 25, 2014 · Viewed 23.5k times · Source

i use ths method to find the difference between two timestamp and get the number of seconds between those two times, and i refresh the information with jquery like a counter.

$diff = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
$time = intval(date('s', $diff));
echo $time;

When the difference is more than 60 seconds, the $time comes back to 0, like a reset.

i would like to display 1 min XX s for example

Answer

John Conde picture John Conde · Jun 25, 2014

The s flag for date() will never return a value greater than 59 as it only represents the current number of seconds of a given time which can never be more than 59 before rolling over into a new minute.

If you want the total number of seconds you can actually remove your second line of code as the difference between two Unix Timestamps is always in seconds:

$time = strtotime(date('Y-m-d H:i:s')) - strtotime('2014-06-25 14:50:03');
echo $time;

If you want to display this as minutes and seconds you can use DateTime() which offers better tools for this:

$now = new DateTime();
$then = new DateTime('2014-06-25 14:50:03');
$diff = $now->diff($then);
echo $diff->format('%i minutes %s seconds');