Sébastien
Sébastien

Reputation: 5463

PHP : How to format seconds to this date string format?

I have a php variable, $seconds = a number of seconds.

I want to convert this value to a string format : 'xxh xxmin xxs' where xx is the value and does not appear if null.

I am currently using the followiing code which works well :

$hours = floor($seconds/3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds/60);
$seconds -= $minutes *60;

$string='';
if ($hours) $string .= $hours . 'h';
$string = $string ? $string . ' ' : $string;
if ($minutes) $string.= $minutes .'min';
$string = $string ? $string . ' ' : $string;
if ($seconds) $string .= $seconds . 's';

return trim($string);

Would there not be a direct way of doing this with gmdate ? The following keeps values when null, not what I'm looking for.

gmdate('H\h i\m\i\n s\s', $duration) : '';

Upvotes: 0

Views: 1288

Answers (1)

Rizier123
Rizier123

Reputation: 59701

Just create a DateTime object, set it to 00:00:00 and then you can just add your seconds with modify(), like this:

<?php

    $seconds = 350;

    $date = new DateTime("00:00:00");
    $date->modify("+ $seconds seconds");
    echo $date->format("H:i:s");

?>

output:

00:05:50

EDIT:

If you don't want to show the value if it is 0, then just use this:

echo implode(" ", array_filter(explode(":", $date->format("H\h:i\m\i\\n:s\s")), function($v){return $v != 0;}));

output:

05min 50s

Upvotes: 3

Related Questions