I have multiple rows with time
"42 sec"
"1 min"
"2 h 32 min"
Is it possible to convert this to
"00:00:42"
"00:01:00"
"02:32:00"
with php?
I have multiple rows with time
"42 sec"
"1 min"
"2 h 32 min"
Is it possible to convert this to
"00:00:42"
"00:01:00"
"02:32:00"
with php?
Not the cleanest solution, but it works for your three cases:
<?
$time[] = "42 sec";
$time[] = "1 min";
$time[] = "2 h 32min";
$seconds = '/([\d]{1,})\s?sec/';
$minutes = '/([\d]{1,})\s?min/';
$hours = '/([\d]{1,})\s?h/';
foreach( $time as $t )
{
echo '<br />';
preg_match( $hours, $t, $h );
$hour = $h[1];
if( $hour )
{
if( strlen( $hour )<2 )
$hour = '0' . $hour;
}
else
$hour = '00';
preg_match( $minutes, $t, $m );
$min = $m[1];
if( $min )
{
if( strlen( $min )<2 )
$min = '0' . $min;
}
else
$min = '00';
preg_match( $seconds, $t, $s );
$sec = $s[1];
if( $sec )
{
if( strlen( $sec )<2 )
$sec = '0' . $sec;
}
else
$sec = '00';
echo $hour . ':' . $min . ':' . $sec;
}
?>
Outputs:
00:00:42
00:01:00
02:32:00
I'm pretty sure there's a better solution, but that one works.
function timetotime($str) {
$match = null;
if (preg_match("/(\d+)(\s?)h/", $str, &$match)) {
$h = $match[1];
if ($h < 10)
$result = "0{$h}:";
else
$result = "{$h}:";
} else
$result = "00:";
if (preg_match("/(\d+)(\s?)min/", $str, &$match)) {
$h = $match[1];
if ($h < 10)
$result .= "0{$h}:";
else
$result .= "{$h}:";
} else
$result .= "00:";
if (preg_match("/(\d+)(\s?)sec/", $str, &$match)) {
$h = $match[1];
if ($h < 10)
$result .= "0{$h}";
else
$result .= "{$h}";
} else
$result .= "00";
return $result;
}
PHP's strtotime()
is a useful function that can convert a string representation of a time into a unix timestamp. From that we can then convert the time into any format we like.
However, your original time strings aren't in a format that strtotime()
can handle directly. eg. 'h' must be 'hour'. But we could perhaps replace these before passing to strtotime() if your data is consistent.
Note we attempt to convert the original time relative to 0, not the current time.
$rawTimes = array ('42 sec', '1 min', '2 h 32min');
foreach ($rawTimes as $rawTime) {
// Convert into a format that strtotime() can understand
$rawTime = str_replace('h','hour',$rawTime);
echo '"'.$rawTime.'" = "'.gmdate('H:i:s',strtotime($rawTime,0)).'"'."\n";
}
Will output:
"42 sec" = "00:00:42"
"1 min" = "00:01:00"
"2 hour 32min" = "02:32:00"
Note that strtotime()
understands 'sec', 'second', 'min', 'minute' and 'hour'. And appears to handle space or no space OK eg. '32min' or '32 min' is handled OK.