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

将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.

  • 写回答

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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题