我想将我的持续时间从1h 20m 53s
转换为01:20:53
格式。我的持续时间可能只有20m 53s
或25m
或1h
或23s
。我需要将其转换为00:00:00
的时间格式。
答案 0 :(得分:4)
您可以使用^(?:(?<hours>\d+)h\s*)?(?:(?<minutes>\d+)m\s*)?(?:(?<seconds>\d+)s\s*)?$
和sprintf
的正则表达式来确保前缀为零:
<?php
function translateTime($timeString) {
if (preg_match('/^(?:(?<hours>\d+)h\s*)?(?:(?<minutes>\d+)m\s*)?(?:(?<seconds>\d+)s\s*)?$/', $timeString, $matches)) {
return sprintf(
'%02s:%02s:%02s',
(!empty($matches['hours']) ? $matches['hours'] : '00'),
(!empty($matches['minutes']) ? $matches['minutes'] : '00'),
(!empty($matches['seconds']) ? $matches['seconds'] : '00')
);
}
return '00:00:00';
}
var_dump( translateTime('1h 20m 53s') ); //string(8) "01:20:53"
var_dump( translateTime('20m 53s') ); //string(8) "00:20:53"
var_dump( translateTime('53s') ); //string(8) "00:00:53"
var_dump( translateTime('1h 30s') ); //string(8) "01:00:30"
var_dump( translateTime('2h 3m') ); //string(8) "02:03:00"
看起来可怕的是,正则表达式只是一堆命名的捕获组:
\s
是空格字符(空格,制表符,\r
,\n
,\f
)
\d
是一个数字(0
,1
,2
,3
,4
,5
,6
,7
,8
,9
)
答案 1 :(得分:0)
首先使字符串与php DateTime对象兼容
$time = preg_split( "/(h|m|s)/i", " 1H 20m 53s " , null, PREG_SPLIT_DELIM_CAPTURE);
$h = 0;
$m = 0;
$s = 0;
$count = count($time);
if ($count == 7)
{
${strtolower($time[1])} = $time[0];
${strtolower($time[3])} = $time[2];
${strtolower($time[5])} = $time[4];
}
else if ($count == 5)
{
${strtolower($time[1])} = $time[0];
${strtolower($time[3])} = $time[2];
}
else if ($count == 3)
{
${strtolower($time[1])} = $time[0];
}
$date = new \DateTime();
$date->setTime($h, $m, $s);
echo $date->format('H:i:s');
您现在可以以任何格式发布它,日期时间支持