In $periods
array first column is for single day (1 godinu), second is for more then one (2 godine) and third is the same but after 4 days in my country, we say different (5 godina).
And it is different for everything, here is an example for all of them:
year = (1 = godinu), (2,3,4 = godine), (after 4 = godina)
month = (1 = mesec), (2,3,4 = meseca), (after 4 = meseci)
week = (1 = nedelju), (2,3,4 = nedelje), (after 4 = nedelja)
day = (1 = dan), (after 1 = dana)
hour = (1 = sat), (2,3,4 = sata), (after 4 = sati)
minute = (1 = minut), (after 1 = minuta)
second = (1 = sekund), (2,3,4 = sekunde), (after 4 = sekundi)
<?php
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$periods = array(
'y' => ['godinu', 'godine', 'godina'],
'm' => ['mesec', 'meseca', 'meseci'],
'w' => ['nedelju', 'nedelje', 'nedelja'],
'd' => ['dan', 'dana', 'dana'],
'h' => ['sat', 'sata', 'sati'],
'i' => ['minut', 'minuta', 'minuta'],
's' => ['sekund', 'sekunde', 'sekundi']
);
$parts = array();
foreach ($periods as $k => &$v) {
if ($diff->$k) {
$parts[] = $diff->$k . ' ' . $v[$diff->$k > 1];
}
}
if (!$full) $parts = array_slice($parts, 0, 1);
return $parts ? 'pre ' . implode(', ', $parts) : DATE_NOW;
}
?>
CodePudding user response:
The correct units for each value can easily be chosen using a simple switch
statement.
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$periods = array(
'y' => ['godinu', 'godine', 'godina'],
'm' => ['mesec', 'meseca', 'meseci'],
'w' => ['nedelju', 'nedelje', 'nedelja'],
'd' => ['dan', 'dana', 'dana'],
'h' => ['sat', 'sata', 'sati'],
'i' => ['minut', 'minuta', 'minuta'],
's' => ['sekund', 'sekunde', 'sekundi']
);
$parts = array();
foreach ($periods as $k => $v) {
if ($diff->$k) {
switch ($diff->$k) {
case 1:
$unit = $v[0];
break;
case 2:
case 3:
case 4:
$unit = $v[1];
break;
default:
$unit = $v[2];
}
$parts[] = $diff->$k . ' ' . $unit;
}
}
if (!$full) $parts = array_slice($parts, 0, 1);
return $parts ? 'pre ' . implode(', ', $parts) : DATE_NOW;
}
echo time_elapsed_string('last month -8days -3hours', true);
// pre 1 mesec, 1 nedelju, 1 dan, 2 sata, 59 minuta, 59 sekundi