Convert Seconds Into Time String In PHP

Here’s a very simple PHP snippet that’s so simple, I’m pretty sure even novice programmers will appreciate it. It’s a return function that takes the numeric value of time given in seconds and then converts it into a string by returning its value in days, hours, minutes and seconds.

ScreenHunter 141 Sep. 05 10.21 Convert Seconds Into Time String In PHP

Example: a value of 654321 will return “7 days, 13 hours, 45 minutes, 21 seconds”

Here’s the code:

<?php
function convertSecToStr($secs){
 $output = '';
 if($secs >= 86400) {
 $days = floor($secs/86400);
 $secs = $secs%86400;
 $output = $days.' day';
 if($days != 1) $output .= 's';
 if($secs > 0) $output .= ', ';
 }
 if($secs>=3600){
 $hours = floor($secs/3600);
 $secs = $secs%3600;
 $output .= $hours.' hour';
 if($hours != 1) $output .= 's';
 if($secs > 0) $output .= ', ';
 }
 if($secs>=60){
 $minutes = floor($secs/60);
 $secs = $secs%60;
 $output .= $minutes.' minute';
 if($minutes != 1) $output .= 's';
 if($secs > 0) $output .= ', ';
 }
 $output .= $secs.' second';
 if($secs != 1) $output .= 's';
 return $output;
}
?>     

Incoming search terms for the article:

Related Posts

Correctly Embed Watermarks In Portrait And Landscape Photos Using Conditional Actions In Photoshop CS6.1

Oregon-Inspired Photoshop Tutorial

Create Google Play’s Tab Navigation Using jQuery And CSS

PS Advanced Compositioning