det kunne være meget mere praktisk, hvis du bruger PHP's DateTime
og DateInterval
klasser og deres metoder:
function timeSince($datetime) {
$now = strtotime("now");
$then = strtotime($datetime);
$dt_now = new DateTime("@" . $now);
$dt_then = new DateTime("@" . $then);
//DateTime's diff method returns a DateInterval object which got a format method:
return $dt_now->diff($dt_then)->format('%a days, %h hours, %i minutes and %s seconds');
}
nogle testcases:
//my local date & time is around "2016-02-25 19:49:00" when testing
echo '<pre>';
echo timeSince('2016-02-25 19:30:00');
//0 days, 0 hours, 19 minutes and 11 seconds
echo PHP_EOL;
echo timeSince('2013-11-02 15:43:12');
//845 days, 4 hours, 4 minutes and 3 seconds
echo PHP_EOL;
echo timeSince('2017-01-31 00:22:45');
//340 days, 4 hours, 35 minutes and 30 seconds
echo PHP_EOL;
echo timeSince('1950-05-14 07:10:05');
//24028 days, 12 hours, 37 minutes and 10 seconds
echo PHP_EOL;
kode delvist baseret på dette svar:https://stackoverflow.com/a/19680778/3391783