3v4l.org

run code in 300+ PHP versions simultaneously
<?php function secondsToTime($seconds) { $dtF = new \DateTime('@0'); $dtT = new \DateTime("@$seconds"); $diff = $dtF->diff($dtT); $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second' ]; foreach ($units as $char => $unit) { if ($diff->$char) { if ($char === 'd' && $diff->$char >= 7) { $diff->$char = floor($diff->$char / 7); $unit = 'week'; } return sprintf( '%d %s%s ago', $diff->$char, $unit, $diff->$char !== 1 ? 's' : '' ); } } } $tests = [ 53 => 53, // y=0, m=0, d=0, h=0, i=0, s=53 365 => 365, // y=0, m=0, d=0, h=0, i=6, s=5 7200 => 7200, // y=0, m=0, d=0, h=2, i=0, s=0 176455 => 176455, // y=0, m=0, d=2, h=1, i=0, s=55 2002000 => 2002000, // y=0, m=0, d=23, h=4, i=6, s=40 4592000 => 4592000, // y=0, m=1, d=22, h=3, i=33, s=20 66536000 => 66536000 // y=2, m=1, d=9, h=2, i=13, s=20 ]; var_export(array_map('secondsToTime',$tests));
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.26, 7.4.0 - 7.4.13, 8.0.0 - 8.0.2
array ( 53 => '53 seconds ago', 365 => '6 minutes ago', 7200 => '2 hours ago', 176455 => '2 days ago', 2002000 => '3 weeks ago', 4592000 => '1 month ago', 66536000 => '2 years ago', )