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. Anonymous
    2013/11/17 at 5:30 pm | #1

    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”;
    }

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

    $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);

  3. 2013/01/18 at 3:44 am | #3

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

  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: