PHPのDateTime
を使用すると、はるかに便利になる可能性があります。 およびDateInterval
クラスとそのメソッド:
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');
}
いくつかのテストケース:
//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;
この回答に部分的に基づいたコード: https://stackoverflow.com/a/19680778/3391783