Home > PHP, Snippets of Code > PHP function to convert seconds into human readable format: months, days, hours, minutes, …

PHP function to convert seconds into human readable format: months, days, hours, minutes, …

This is a simple PHP code that converts a number of seconds into a string according to the following format: M d h m s.

function seconds2human($ss) {
$s = $ss%60;
$m = floor(($ss%3600)/60);
$h = floor(($ss%86400)/3600);
$d = floor(($ss%2592000)/86400);
$M = floor($ss/2592000);

return "$M months, $d days, $h hours, $m minutes, $s seconds";
}

Number of months is an approx calculation supposing months are 30 days long.

About these ads
Categories: PHP, Snippets of Code
  1. 2015/03/17 at 4:29 am

    who chenge (php time to hours)?

    <?PHP
    if ($row["rep_status"]=="2") {
    $day_frame=getWorkingDays($rep_rec_date,$rep_close_date,$holidays);

    // $day_frame=daysDifference ($rep_close_date,$rep_rec_date);
    // if ($day_frame 5 Days”;
    // }
    } else {
    echo ” “;
    }
    ?>

  2. Anonymous
    2013/11/17 at 5:30 pm

    slight modification to prevent results like: 0 months, 0 days, 0 hours, 0 minutes, 12 seconds

    function seconds2human($ss) {
    $s = $ss % 60;
    $m = (floor(($ss%3600)/60)>0)?floor(($ss%3600)/60).’ minutes':”;
    $h = (floor(($ss % 86400) / 3600)>0)?floor(($ss % 86400) / 3600).’ hours':”;
    $d = (floor(($ss % 2592000) / 86400)>0)?floor(($ss % 2592000) / 86400).’ days':”;
    $M = (floor($ss / 2592000)>0)?floor($ss / 2592000).’ months':”;

    return “$M $d $h $m $s seconds”;
    }

  3. msi saurovh
    2013/06/12 at 2:25 pm

    $d = floor(($ss%2592000)/86400);
    $M = floor($ss/2592000);
    echo ($M > 0)?”$M months, “:”;
    echo ($d > 0)?”$d days “:”;
    echo gmdate(“H:i:s”,$ss);

  4. 2013/01/18 at 3:44 am

    WOW! Short. Sweet. And does exactly what I’ve been trying to do with strtotime() and gmdate(). Thanks for sharing this link on stackoverflow.

    • 2013/04/26 at 6:02 pm

      Thanks, that’s the idea, short but useful copy/past code.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: