Converting Seconds into Days, Hours, and Minutes

I’m going to let you know how to turn second into date format in this quick tutorial, which is a common challenge for web development, in order to convert date into a certain date format.

We must translate the date from timetable to the desired data format by using the date function (timestamp, ‘date format’), to obtain the above results.

However, Here we convert seconds to a user-specific date format, like we would like to display below.

“14 days, six hours, 56 minutes, seven seconds”

You can also check other recommended Date PHP tutorials,

The simple hours formula:
hours = seconds ÷ 3,600

The time in hours is equal to the time in seconds divided by 3,600. Since there are 3,600 seconds in one hour, that’s the conversion ratio used in the formula.

PHP Function to Convert seconds to Days, Hours, Minutes and Seconds

We can create a custom PHP function to handle this conversion. Here’s an example function:

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

Simple usage:

echo secsToStr(90360);

Output:

1 day, 1 hour, 6 minutes 0 seconds

Option 2: Convert Seconds to Days, Hours and Minutes

The following code is simple, for turning seconds independently or blended into days, hours and minutes.

function secToDaysHoursMinutes($seconds) {
    $days = floor($seconds/86400);
    $hours = floor(($seconds - $days*86400) / 3600);
    $minutes = floor(($seconds / 60) % 60);
    return "$days days, $hours hours, $minutes minutes";
}

We have passed a variable $seconds into this method. Then we converted the seconds into hours, minutes, and seconds respectively.

Simple usage:

echo secToDaysHoursMinutes(90360);

Output:

1 days:1 hours:6 minutes

Conclusion

Converting seconds into days, hours, and minutes is essential for displaying time durations in a human-readable format. We have created two methods secsToStr() or secToDaysHoursMinutes() to solve this problem.

Leave a Reply

Your email address will not be published.