doutouman6245
2014-04-08 10:52
浏览 120
已采纳

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

I want to convert my time duration from 1h 20m 53s into 01:20:53 format. My time duration may only have 20m 53s or 25m or 1h or 23s. I need to convert that into time format of 00:00:00.

图片转代码服务由CSDN问答提供 功能建议

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglv6960 2014-04-08 11:06
    已采纳

    You can use a regex of ^(?:(?<hours>\d+)h\s*)?(?:(?<minutes>\d+)m\s*)?(?:(?<seconds>\d+)s\s*)?$ and sprintf to make sure that zeroes are prepended:

    <?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

    While looking scary the regex is just a bunch of named capture groups:

    Regular expression visualization

    \s is a white space character (space, tab, , , \f)
    \d is a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

    已采纳该答案
    打赏 评论
  • doujiao8649 2014-04-08 11:07

    first make the string compatible with php DateTime object

    $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');
    

    you can now post it in any format php DateTime supports

    打赏 评论

相关推荐 更多相似问题