<?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.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- 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',
)
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
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',
)
preferences:
189.37 ms | 402 KiB | 181 Q