[php] How to convert seconds to time format?

For some reason I convert a time format like: 03:30 to seconds 3*3600 + 30*60, now. I wanna convert it back to its first (same) format up there. How could that be?

My attempt:

3*3600 + 30*60 = 12600 

12600 / 60 = 210 / 60 = 3.5, floor(3.5) = 3 = hour

Now, what about the minutes?

Considering the value can be like 19:00 or 02:51. I think you got the picture.

And by the way, how to convert 2:0 for example to 02:00 using RegEx?

This question is related to php time format

The answer is


Sorry this is too late but maybe useful

function mediaTimeDeFormater($seconds)
{
    if (!is_numeric($seconds))
        throw new Exception("Invalid Parameter Type!");


    $ret = "";

    $hours = (string )floor($seconds / 3600);
    $secs = (string )$seconds % 60;
    $mins = (string )floor(($seconds - ($hours * 3600)) / 60);

    if (strlen($hours) == 1)
        $hours = "0" . $hours;
    if (strlen($secs) == 1)
        $secs = "0" . $secs;
    if (strlen($mins) == 1)
        $mins = "0" . $mins;

    if ($hours == 0)
        $ret = "$mins:$secs";
    else
        $ret = "$hours:$mins:$secs";

    return $ret;
}

echo mediaTimeDeFormater(216.064000);//3:36

Maybe the simplest way is:

gmdate('H:i:s', $your_time_in_seconds);

Another solution that will give you the days, hours, minutes, and seconds for a passed-in seconds value:

function seconds_to_time($secs)
{
    $dt = new DateTime('@' . $secs, new DateTimeZone('UTC'));
    return array('days'    => $dt->format('z'),
                 'hours'   => $dt->format('G'),
                 'minutes' => $dt->format('i'),
                 'seconds' => $dt->format('s'));
}

print_r(seconds_to_time($seconds_value);

Extra logic will be needed for 'days' if the time is expected to be more than one year. Use str_pad() or ltrim() to add/remove leading zeros.


This might be simpler

gmdate("H:i:s", $seconds)

PHP gmdate


If the you know the times will be less than an hour, you could just use the date() or $date->format() functions.

$minsandsecs = date('i:s',$numberofsecs);

This works because the system epoch time begins at midnight (on 1 Jan 1970, but that's not important for you).

If it's an hour or more but less than a day, you could output it in hours:mins:secs format with `

$hoursminsandsecs = date('H:i:s',$numberofsecs);

For more than a day, you'll need to use modulus to calculate the number of days, as this is where the start date of the epoch would become relevant.

Hope that helps.


If You want nice format like: 0:00:00 use str_pad() as @Gardner.


Use modulo:

$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;

Let $time be the time as number of seconds.

$seconds = $time % 60;
$time = ($time - $seconds) / 60;
$minutes = $time % 60;
$hours = ($time - $minutes) / 60;

Now the hours, minutes and seconds are in $hours, $minutes and $seconds respectively.


1 day = 86400000 milliseconds.

DecodeTime(milliseconds/86400000,hr,min,sec,msec)

Ups! I was thinking in delphi, there must be something similar in all languages.


just one small additional example

requested time in miliseconds

    // ms2time( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array
    function ms2time($ms){
        $return = array();
        // ms
        $return['ms'] = (int) number_format( ($ms - (int) $ms), 2, '', '');
        $seconds = (int) $ms;
        unset($ms);

        if ($seconds%60 > 0){
            $return['s'] = $seconds%60;
        } else {
            $return['s'] = 0;
        }

        if ( ($minutes = intval($seconds/60))){
            $return['m'] = $minutes;
        }

        if (isset($return['m'])){
            $return['h'] = intval($return['m'] / 60);
            $return['m']  = $return['m'] % 60; 
        }


        if (isset($return['h'])){
            $return['d'] = intval($return['h'] / 24);
            $return['h']  = $return['h'] % 24; 
        }

        if (isset($return['d']))
            $return['mo'] = intval($return['d'] / 30);

        foreach($return as $k=>$v){
            if ($v == 0)
                unset($return[$k]);
        }

        return $return;
    }

    // ms2time2string( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array     
    function ms2time2string($ms){
        $array = array(
            'ms' => 'ms',
            's'  => 'seconds',
            'm'  => 'minutes',
            'h'  => 'hours',
            'd'  => 'days',
            'mo' => 'month',
        );


        if ( ( $return = ms2time($ms) )  && count($ms) > 0){

            foreach($return as $key=>$data){
                $return[$key] = $data .' '.$array[$key];
            }

        }
        return implode(" ", array_reverse($return));
    }

Here is another way with leading '0' for all of them.

$secCount = 10000;
$hours = str_pad(floor($secCount / (60*60)), 2, '0', STR_PAD_LEFT);
$minutes = str_pad(floor(($secCount - $hours*60*60)/60), 2, '0', STR_PAD_LEFT);
$seconds = str_pad(floor($secCount - ($hours*60*60 + $minutes*60)), 2, '0', STR_PAD_LEFT);

It is an adaptation from the answer of Flaxious.


ITroubs answer doesn't deal with the left over seconds when you want to use this code to convert an amount of seconds to a time format like hours : minutes : seconds

Here is what I did to deal with this: (This also adds a leading zero to one-digit minutes and seconds)

$seconds = 3921; //example

$hours = floor($seconds / 3600);
$mins = floor(($seconds - $hours*3600) / 60);
$s = $seconds - ($hours*3600 + $mins*60);

$mins = ($mins<10?"0".$mins:"".$mins);
$s = ($s<10?"0".$s:"".$s); 

$time = ($hours>0?$hours.":":"").$mins.":".$s;

$time will contain "1:05:21" in this example.


something like this?

if(is_numeric($time)){
    $value = array(
        "years" => 0, "days" => 0, "hours" => 0,
        "minutes" => 0, "seconds" => 0,
    );
    if($time >= 31556926){
        $value["years"] = floor($time/31556926);
        $time = ($time%31556926);
    }
    if($time >= 86400){
        $value["days"] = floor($time/86400);
        $time = ($time%86400);
    }
    if($time >= 3600){
        $value["hours"] = floor($time/3600);
        $time = ($time%3600);
    }
    if($time >= 60){
        $value["minutes"] = floor($time/60);
        $time = ($time%60);
    }

    $value["seconds"] = floor($time);
    return (array) $value;
    
} else{
    return (bool) FALSE;
}

grabbed from: http://www.ckorp.net/sec2time.php


If you were to hardcode it you would use modulus to extract the time as others suggested.

If you are returning the seconds from MySQL database, assuming you don't need the data in seconds format in your app, there is a much cleaner way to do it, you can use MySQL's SEC_TO_TIME and it will return time in hh:mm:ss format.

Eg.

SELECT SEC_TO_TIME(my_seconds_field) AS my_timestring;

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?