I understand that you wish to show only the values that aren't zero.
This will require a bit of work. You need to get the individual values from the interval and see if they are zero, and get only the ones that aren't.
You can put those values on an array and join them, but you need to know what each value represents, so you need some form of label (years, months, etc).
You'll also need to remove the s
from the label if the value is 1
, so that's simple: you just need to check if the value is 1 and take the substring of the label without the last character (substr($str, 0, -1)
).
Then you could just join those values with a comma, but you won't have the "and" part in the last index, so you have to check if there is more than one item in your array and join the last one with an "and" string.
This is the final result:
<?php
function convertSecToTime($sec)
{
$date1 = new DateTime("@0");
$date2 = new DateTime("@$sec");
$interval = date_diff($date1, $date2);
$parts = ['years' => 'y', 'months' => 'm', 'days' => 'd', 'hours' => 'h', 'minutes' => 'i', 'seconds' => 's'];
$formatted = [];
foreach($parts as $i => $part)
{
$value = $interval->$part;
if ($value !== 0)
{
if ($value == 1){
$i = substr($i, 0, -1);
}
$formatted[] = "$value $i";
}
}
if (count($formatted) == 1)
{
return $formatted[0];
}
else
{
$str = implode(', ', array_slice($formatted, 0, -1));
$str.= ' and ' . $formatted[count($formatted) - 1];
return $str;
}
}
echo convertSecToTime(500); //8 minutes and 20 seconds
echo convertSecToTime(1500); //25 minutes
echo convertSecToTime(2500); //41 minutes and 40 seconds
echo convertSecToTime(3500); //58 minutes and 20 seconds
echo convertSecToTime(4500); //1 hour and 15 minutes
echo convertSecToTime(5500); //1 hour, 31 minutes and 40 seconds