Quantcast
Channel: PHP Website Development » PH
Viewing all articles
Browse latest Browse all 11

How do you convert 00:00:00 to hours, minutes, seconds in PH

$
0
0

I have video durations stored in HH:MM:SS format. I’d like to display it as HH hours, MM minutes, SS seconds. It shouldn’t display hours if it’s less than 1.
What would be the best approach?
…………………………………

try using split
list($hh,$mm,$ss)= split(‘:’,$duration);
…………………………………

Something like this?
$vals = explode(‘:’, $duration); if ( $vals[0] == 0 ) $result = $vals[1] . ‘ minutes, ‘ . $vals[2] . ‘ seconds’; else $result = $vals[0] . ‘hours, ‘ . $vals[1] . ‘ minutes, ‘ . $vals[2] . ‘ seconds’;
…………………………………

One little change could be:
$vals = explode(‘:’, $duration); if ( $vals[0] == 0 ) $result = “{$vals[1]} minutes, {$vals[2]} seconds”; else $result = “{$vals[0]} hours, {$vals[1]} minutes, {$vals[2]} seconds”;
…………………………………

Pretty simple:
list( $h, $m, $s) = explode(‘:’, $hms); echo ($h ? “$h hours, ” : “”).($m ? “$m minutes, ” : “”).(($h || $m) ? “and ” : “”).”$s seconds”; This will only display the hours or minutes if there are any, and inserts an “and” before the seconds if there are hours, minutes, or both to display. If you wanted to get really fancy, you could add some code to display “hour” vs. “hours” as appropriate, ditto for minutes and seconds.
…………………………………

Why bother with regex or explodes when php handles time just fine?
$sTime = ’04:20:00′; $oTime = new DateTime($sTime); $aOutput = array(); if ($oTime->format(‘G’) > 0) { $aOutput[] = $oTime->format(‘G’) . ‘ hours’; } $aOutput[] = $oTime->format(‘i’) . ‘ minutes’; $aOutput[] = $oTime->format(‘s’) . ‘ seconds’; echo implode(‘, ‘, $aOutput); The benefit is that you can reformat the time however you like (including am/pm, adjustments for timezone, addition / subtraction, etc).


Viewing all articles
Browse latest Browse all 11

Trending Articles