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
.
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"
While looking scary the regex is just a bunch of named capture groups:
\s
is a white space character (space, tab, ,
,
\f
)\d
is a digit (0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
)
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