将JIRA时间日志#h #m #s格式的持续时间转换为00:00:00

时间:2014-04-08 10:52:48

标签: php

我想将我的持续时间从1h 20m 53s转换为01:20:53格式。我的持续时间可能只有20m 53s25m1h23s。我需要将其转换为00:00:00的时间格式。

2 个答案:

答案 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"

DEMO

看起来可怕的是,正则表达式只是一堆命名的捕获组:

Regular expression visualization

\s是空格字符(空格,制表符,\r\n\f
\d是一个数字(0123456789

答案 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');

您现在可以以任何格式发布它,日期时间支持