PHP time to days hours seconds function

Hi Guys,

I thought I should share this useful code snippet with you that will convert time in seconds to Days Hours Minutes Seconds format

Here is the function

  1. function timeBeautifier($seconds_val){
  2. $returnstring = " ";
  3. $dd = intval($seconds_val/86400);
  4. $hh = intval ( ($seconds_val/3600) - ($dd*24));
  5. $mm = intval( ($seconds_val - (($dd*86400)+ ($hh*3600)))/60);
  6. $secs = $seconds_val - ( ($dd*86400)+($hh*3600)+($mm * 60));
  7.  
  8. $returnstring .= ($dd)?(($dd == 1)? "1 day":$dd." days"):"";
  9. $returnstring .= ($dd && $hh && !$mm && !$secs)?" and ":" ";
  10. $returnstring .= ($hh)?( ($hh == 1)?"1 hour":$hh." hours"):"";
  11. $returnstring .= (($dd || $hh) && ($mm && !$secs))?" and ":" ";
  12. $returnstring .= ($mm)?( ($mm == 1)?"1 minute":"$mm minutes"):"";
  13. $returnstring .= (($dd || $hh || $mm) && $secs)?" and ":" ";
  14. $returnstring .= ($secs)?( ($secs == 1)?"1 second":$secs." seconds"):"";
  15. return ($returnstring);
  16. }

You can easily extend this function to include year/month/weeks information if you like.

Let me show you the way you can use this function

Code below

  1. echo timeBeautifier(86400);

will result in output

1 Day

Code below

  1. echo timeBeautifier(86410);

will result in output

1 Day and 10 seconds

  1. echo timeBeautifier(5648);

will result in output

1 hour 34 minutes and 8 seconds

I hope that this code snippet will be useful to you.

If you end up modifying this code please share it using comments so that others can benefit.

Cheers

Advertisement

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge