Guillaume Bois
Guillaume Bois

Reputation: 1331

Get formated time for a video duration in php

This should be easy...

I have a duration in seconds, I want to output it in hours:minutes:seconds format

When I try...

// video duration is 1560 seconds

<?=date("h:i:s",$video->duration)?>

...it outputs 07:26:00 instead of 00:26:00. So I figure it's a time zone issue.

At the beginning of my application I set the timezone like this

date_default_timezone_set('America/Montreal');

Now I guess I would get my normal value if I change the timezone to GMT but I don't want to do that each time I want a simple duration (and re-set the timezone to America/Montreal)

What are my options?

Upvotes: 0

Views: 1833

Answers (2)

syrkull
syrkull

Reputation: 2344

This is an old question but I thought I can provide an answer for this:

function convert_to_duration($total_time){
    $seconds = $total_time %60;
    $minutes = (floor($total_time/60)) % 60;
    $hours = floor($total_time/3600);
    if($hours == 0){
        return $minutes . ':' . sprintf('%02d', $seconds);
    }else{
        return $hours . ':' . $minutes . ':' . sprintf('%02d', $seconds);
    }
}

Upvotes: 0

mishu
mishu

Reputation: 5397

date is used to get a human readable format for an unix timestamp, so it's not what you need. In other words that function is used to show a date (like 12.12.2012) and not the duration of your video

for that you can create a function that starts from the total number of seconds and does something like

$seconds = $total_time %60;
$minutes = (floor($total_time/60)) % 60;
$hours = floor($total_time/3600);
return $hours . ':' . $minutes . ':' . $seconds;

maybe you need to adjust this a bit, as I did not test it. also some tests to skip hours or minutes if the video is short

Upvotes: 1

Related Questions