Andres
Andres

Reputation: 2023

php convert seconds to timestamp

I have a total seconds value in my table but I would like to get a time format like hh:mm:ss, currently I have for example: seconds - 226 and I know that should be in time format 4 minutes and 26 seconds, but I've tried this code:

$seconds = 226;
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60); 
$secs = floor(($seconds - ($hours*3600)) - ($mins*60));

and this outputs 3:46

maybe there's something wrong with the formula?

EDIT: I got this value from a youtube scripts that returns duration of video:

    $ytvidid = $url;
$ytdataurl = "http://gdata.youtube.com/feeds/api/videos/". $ytvidid;
$feedURL = $ytdataurl;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feedURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get the result of http query
$output = curl_exec($ch);
curl_close($ch);
// feed the curl output to simplexml_load_string
$sxml = simplexml_load_string($output) or die("XML string not loading");

//$sxml = simplexml_load_file($feedURL);
$media = $sxml->children('http://search.yahoo.com/mrss/');
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
    echo $attrs['seconds'];

Upvotes: 2

Views: 9269

Answers (3)

Leandro Bardelli
Leandro Bardelli

Reputation: 11608

Supericy answer is good, but only works for 24 hours and if you need hours > day then I got something like:

$diffInSeconds = 64;
$h =  floor($diffInSeconds / 3600);
$m =  floor(($diffInSeconds - ($h * 3600)) / 60);
$s =  floor(($diffInSeconds - (($h * 3600) + $m * 60)));

echo sprintf('%02d', $h) . ":" . sprintf('%02d', $m). ":" . sprintf('%02d', $s);

BTW your calculation is fine. But I choose this way.

Upvotes: 0

user3501407
user3501407

Reputation: 457

u can use this one.. this code like youtube time

$total_secs = '15454';

//time settings
$hours = floor($total_secs / 3600);
$mins = floor(($total_secs - ($hours*3600)) / 60);
$secs = floor($total_secs % 60);

//if hours zero, give for nothing like that (45:05)     
if ($hours<1) { $hours = ''; } else { $hours = $hours.':'; }
if ($mins<10) { $mins = '0'.$mins.':'; } else { $mins = $mins.':'; }
if ($secs<10) { $secs = '0'.$secs; } else { $secs = $secs; }

echo $output = $hours.$mins.$secs; //

Upvotes: 1

Supericy
Supericy

Reputation: 5896

Use the gmdate function, you can view the format codes at http://php.net/manual/en/function.date.php

echo gmdate("H:i:s", $seconds);

PS. Your method already works. 226 seconds would be 3 minutes and 46 seconds.

Upvotes: 6

Related Questions