Jump to content

Duration help


DieSucker

Recommended Posts

So i have this duration code

[code]
function duration($timestamp) {
    
    $years=floor($timestamp / (60*60*24*365));
    $timestamp%=60*60*24*365;
    
    $weeks=floor($timestamp / (60*60*24*7));
    $timestamp%=60*60*24*7;
    
    $days=floor($timestamp / (60*60*24));
    $timestamp%=60*60*24;
    
    $hrs=floor($timestamp / (60*60));
    $timestamp%=60*60;
    
    $mins=floor($timestamp / 60);
    $secs=$timestamp % 60;
  
   $str="";

   if ($years >= 1) { $str.="{$years} years "; }
   if ($weeks >= 1) { $str.="{$weeks} weeks "; }
   if ($days >= 1) { $str.="{$days} days "; }
   if ($hrs >= 1) { $str.="{$hrs} hours "; }
   if ($mins >= 1) { $str.="{$mins}"; }
   if ($secs >= 10) { $str.=":{$secs}"; }
   if ($secs < 10) { $str.=":0{$secs}"; }
  
   return $str;
}[/code]

which I am using for unixdate. Right now the out put would be like "1:45" and for just seconds it would output
":45" my problem is how do I get it to add "00" before the colon if the duration is just seconds
Any ideas?
Link to comment
Share on other sites

I would try putting your code as this instead:

[code]

   if ($years >= 1) { $str.="{$years} years "; }
   if ($weeks >= 1) { $str.="{$weeks} weeks "; }
   if ($days >= 1) { $str.="{$days} days "; }
   if ($hrs >= 1) { $str.="{$hrs} hours "; }
   if ($mins >= 1) { $str.="{$mins}"; }

   // Checks if there are only seconds.
   if ($years < 1 && $weeks < 1 && $days < 1 && hrs < 1 && mins < 1)
      {$str = "00";}
   if ($secs >= 10) { $str.=":{$secs}"; }
   if ($secs < 10) { $str.=":0{$secs}"; }

[/code]

This will first work as you wrote it. When it reaches the comment, it checks to see if there are no years, weeks, days, hours or minutes. If there are not, it will set $str to "00" before finishing the script (then the seconds and colon will be added after the 00, which is what you wanted). If there are any of the above, it will do nothing and proceed as it normally would.

Hope this helps.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.