benjisail
benjisail

Reputation: 1666

How to convert a "HH:MM:SS" string to seconds with PHP?

Is there a native way of doing "HH:MM:SS" to seconds with PHP 5.3 rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?


For example in Python you can do :

string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;

Upvotes: 10

Views: 36331

Answers (4)

proseosoc
proseosoc

Reputation: 1354

This function also supports input without hour or minute

$timeInSecs = function ($tym) {
  $tym = array_reverse(explode(':',$tym));
  $hr = $tym[2] ?? 0;
  $min = $tym[1] ?? 0;
  return $hr*60*60 + $min*60 + $tym[0];
};

echo $timeInSecs('1:1:30') . '<br>'; // output: 3690
echo $timeInSecs('1:30') . '<br>'; // output: 90
echo $timeInSecs('30') . '<br>'; // output: 30

Upvotes: 1

Glavić
Glavić

Reputation: 43552

I think the easiest method would be to use strtotime() function:

$time = '21:30:10';
$seconds = strtotime("1970-01-01 $time UTC");
echo $seconds;

demo


Function date_parse() can also be used for parsing date and time:

$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

demo

Upvotes: 8

Spudley
Spudley

Reputation: 168685

This should do the trick:

list($hours,$mins,$secs) = explode(':',$time);
$seconds = mktime($hours,$mins,$secs) - mktime(0,0,0);

Upvotes: 11

netcoder
netcoder

Reputation: 67695

The quick way:

echo strtotime('01:00:00') - strtotime('TODAY'); // 3600

Upvotes: 29

Related Questions