谢谢你的建议。
对于这种方法,我主要使用了 Waygood 和 ChrisForrence 的建议。我试图让它尽可能简单,并引入了简单的参数,例如细节级别和分隔符(用于字符串输出)。
public function elapsedTimeHumanReadable($date = null, $detailLevel = 2, $delimiter = ' et ')
{
if($date === null)
{
$date = self::now();
}
$sec = $this->elapsedSecond($date);
$a_sec = 1;
$a_min = $a_sec * 60;
$an_hour = $a_min * 60;
$a_day = $an_hour * 24;
$a_month = $a_day * 30;
$a_year = $a_day * 365;
$text = '';
$resultStack = array();
if($sec >= $a_year)
{
$years = floor($sec / $a_year);
$text .= $years . $this->plural($years, ' an');
$sec = $sec - ($years * $a_year);
array_push($resultStack, $text);
}
if($sec >= $a_month)
{
$months = floor($sec / $a_month);
$text = $months . ' mois';
$sec = $sec - ($months * $a_month);
array_push($resultStack, $text);
}
if($sec >= $a_day)
{
$days = floor($sec / $a_day);
$text = $days . $this->plural($days, ' jour');
$sec = $sec - ($days * $a_day);
array_push($resultStack, $text);
}
if($sec >= $an_hour)
{
$hours = floor($sec / $an_hour);
$text = $hours . $this->plural($hours, ' heure');
$sec = $sec - ($hours * $an_hour);
array_push($resultStack, $text);
}
if($sec >= $a_min)
{
$minutes = floor($sec / $a_min);
$text = $minutes . $this->plural($minutes, ' minute');
$sec = $sec - ($minutes * $a_min);
array_push($resultStack, $text);
}
if($sec >= $a_sec)
{
$seconds = floor($sec / $a_sec);
$text = $sec . $this->plural($seconds, ' seconde');
$sec = $sec - ($sec * $a_sec);
array_push($resultStack, $text);
}
$result = $resultStack[0];
for($i = 1; $i <= $detailLevel - 1; $i++)
{
if(!empty($resultStack[$i]))
{
$result .= $delimiter . $resultStack[$i];
}
}
return $result;
}
我还添加了一个非常简单的复数函数以正确的语法方式返回时间单位:
public function plural($value, $unit)
{
if($value > 1)
{
return $unit . 's';
}
else
{
return $unit;
}
}
我对 for 循环不是很满意,但它实际上运行良好。
无论如何,非常感谢您的帮助!