Yasitha
Yasitha

Reputation: 2303

How to convert seconds into HH:mm format php

I am having a time duration in seconds. I want show it in HH:mm format. Is there way to do it using php date-time function??

Upvotes: 1

Views: 3332

Answers (4)

evotopid
evotopid

Reputation: 5429

Use gmdate() and set the seconds as param.

Example:

$seconds = 20;
$result = gmdate('H:i', $seconds);

Edit: Ooops... I placed date instead of gmdate... Now I noticed the problem with the timezones with date.
(It's corrected now.)

Upvotes: 6

Stefan Koenen
Stefan Koenen

Reputation: 2337

i found this solution:

function sec_to_his ($seconds) { return gmdate ('H:i:s', $seconds); }

some other variations can be found on this website: http://codeaid.net/php/convert-seconds-to-hours-minutes-and-seconds-(php)

greets stefan.

Upvotes: 3

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

If you have seconds you could do:

<?php

$sec = 3864;

$h = floor($sec /3600);
$m = floor(($sec - $h *3600) / 60);
$s = $sec % 60;


printf("%02d:%02d:%02d", $h, $m, $s);

?>

output here: http://codepad.org/7ee9Cx03

Upvotes: 5

Martin Bean
Martin Bean

Reputation: 39429

You could write a function:

<?php

function convertToHoursMinutes($seconds) {

    $seconds = intval($seconds);
    $hours = ceil($seconds/3600);
    $minutes = $seconds%3600;

    return sprintf('%d:%02d', $hours, $minutes);
}

echo '24502 seconds is ' . convertToHoursMinutes(24502);

Or you could try searching Google your question.

Upvotes: -2

Related Questions