How to convert seconds to time format?

PhpTimeFormat

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

This might be simpler

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

PHP gmdate

Solution 2 - Php

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

If you want to get time format:

$timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);

Solution 3 - Php

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.

Solution 4 - Php

Maybe the simplest way is:

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

Solution 5 - Php

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.

Solution 6 - Php

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.

Solution 7 - Php

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.

Solution 8 - 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;

Solution 9 - Php

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

Solution 10 - Php

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

Solution 11 - Php

Use modulo:

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

Solution 12 - Php

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));
	}

Solution 13 - Php

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.

Solution 14 - Php

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

Solution 15 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDewan159View Question on Stackoverflow
Solution 1 - PhpCyberJunkieView Answer on Stackoverflow
Solution 2 - PhpITroubsView Answer on Stackoverflow
Solution 3 - PhpSpudleyView Answer on Stackoverflow
Solution 4 - Phpmarco_mantiView Answer on Stackoverflow
Solution 5 - PhpHammeriteView Answer on Stackoverflow
Solution 6 - PhpGZippView Answer on Stackoverflow
Solution 7 - PhpFlaxiousView Answer on Stackoverflow
Solution 8 - PhpJulijan AnđelićView Answer on Stackoverflow
Solution 9 - PhpFatherStormView Answer on Stackoverflow
Solution 10 - PhpSoroush KhosraviView Answer on Stackoverflow
Solution 11 - PhpbitmaskView Answer on Stackoverflow
Solution 12 - PhpOleg ButuzovView Answer on Stackoverflow
Solution 13 - PhpGardnerView Answer on Stackoverflow
Solution 14 - PhpLeszek PietrzakView Answer on Stackoverflow
Solution 15 - PhpGonzaloView Answer on Stackoverflow