Php 将十分之一的时间安排为运动时间
我有一个与运动有关的时间,存储在十分之一秒之内。我需要像h:mm:ss.f那样格式化它们,其中每个部分应该只有在必要时才可见。例如:Php 将十分之一的时间安排为运动时间,php,time,formatting,Php,Time,Formatting,我有一个与运动有关的时间,存储在十分之一秒之内。我需要像h:mm:ss.f那样格式化它们,其中每个部分应该只有在必要时才可见。例如: Tenths Formatted 1 0.1 12 1.2 123 12.3 1 234 2:03.4 12 345 20:34.5 123 456 3:25:45
Tenths Formatted
1 0.1
12 1.2
123 12.3
1 234 2:03.4
12 345 20:34.5
123 456 3:25:45.6
1 234 567 34:17:36.7
12 345 678 342:56:07.8
123 456 789 3429:21:18.9
您将如何在PHP中实现这一点
这是我目前的解决方案,但想知道是否有其他更干净、更高效或更奇特的方法来做到这一点
function sports_format($tenths)
{
$hours = floor($tenths / 36000);
$tenths -= $hours*36000;
$minutes = floor($tenths / 600);
$tenths -= $minutes*600;
$seconds = floor($tenths / 10);
$tenths -= $seconds*10;
$text = sprintf('%u:%02u:%02u.%u',
$hours, $minutes, $seconds, $tenths);
return preg_replace('/^(0|:){1,6}/', '', $text);
}
但我不认为这更清洁。除了在可能的情况下使用正则表达式之外,您的代码很好。聪明!但是,是的,可能不是特别干净:p关于ltrim,您是否能将最后的0保持为0.1中的0?我会检查$tenths是否小于10,然后直接返回0。$tenths。在这种情况下,无需进一步计算
$tenths = (array)$tenths;
$div = array(36000, 600, 10);
while($d = array_shift($div))
$tenths[0] -= ($tenths[] = floor($tenths[0] / $d)) * $d;
$text = vsprintf('%2$u:%3$02u:%4$02u.%u', $tenths);
return ltrim($text, '0:');