Convert seconds to Hour:Minute:Second

前端 未结 27 2168
说谎
说谎 2020-11-22 07:56

I need to convert seconds to \"Hour:Minute:Second\".

For example: \"685\" converted to \"00:11:25\"

How can I achieve this?

27条回答
  •  长发绾君心
    2020-11-22 08:19

    Just in case anyone else is looking for a simple function to return this nicely formatted (I know it is not the format the OP asked for), this is what I've just come up with. Thanks to @mughal for the code this was based on.

    function format_timer_result($time_in_seconds){
        $time_in_seconds = ceil($time_in_seconds);
    
        // Check for 0
        if ($time_in_seconds == 0){
            return 'Less than a second';
        }
    
        // Days
        $days = floor($time_in_seconds / (60 * 60 * 24));
        $time_in_seconds -= $days * (60 * 60 * 24);
    
        // Hours
        $hours = floor($time_in_seconds / (60 * 60));
        $time_in_seconds -= $hours * (60 * 60);
    
        // Minutes
        $minutes = floor($time_in_seconds / 60);
        $time_in_seconds -= $minutes * 60;
    
        // Seconds
        $seconds = floor($time_in_seconds);
    
        // Format for return
        $return = '';
        if ($days > 0){
            $return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
        }
        if ($hours > 0){
            $return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
        }
        if ($minutes > 0){
            $return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
        }
        if ($seconds > 0){
            $return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
        }
        $return = trim($return);
    
        return $return;
    }
    

提交回复
热议问题