简体   繁体   English

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

[英]Convert time duration like in JIRA time log #h #m #s format into 00:00:00

I want to convert my time duration from 1h 20m 53s into 01:20:53 format. 我想将我的持续时间从1h 20m 53s转换为01:20:53格式。 My time duration may only have 20m 53s or 25m or 1h or 23s . 我的持续时间可能只有20m 53s25m1h23s I need to convert that into time format of 00:00:00 . 我需要将其转换为00:00:00时间格式。

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: 您可以使用^(?:(?<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 DEMO

While looking scary the regex is just a bunch of named capture groups: 正则表达式看起来很吓人,只是一堆命名的捕获组:

正则表达式可视化

\\s is a white space character (space, tab, \\r , \\n , \\f ) \\s是一个空白字符(空格,制表符, \\r\\n\\f
\\d is a digit ( 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ) \\d是一个数字( 0123456789

first make the string compatible with php DateTime object 首先使字符串与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');

you can now post it in any format php DateTime supports 您现在可以将其发布为php DateTime支持的任何格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM