Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time in HH:MM:SS format to seconds only?

Tags:

php

time

How to turn time in format HH:MM:SS into a flat seconds number?

P.S. Time could be sometimes in format MM:SS only.

like image 472
CodeOverload Avatar asked Jan 29 '11 00:01

CodeOverload


People also ask

How do you convert HH mm to seconds?

To convert hh:mm:ss to seconds:Convert the hours to seconds, by multiplying by 60 twice. Convert the minutes to seconds by multiplying by 60 .

How do you convert HH mm SS to SEC in Excel?

To convert hh:mm:ss time format to seconds: =HOUR(A2)*3600 + MINUTE(A2)*60 + SECOND(A2).

How do you convert time to seconds?

To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).


2 Answers

No need to explode anything:

$str_time = "23:12:95";  $str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);  sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);  $time_seconds = $hours * 3600 + $minutes * 60 + $seconds; 

And if you don't want to use regular expressions:

$str_time = "2:50";  sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);  $time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes; 
like image 60
Tim Cooper Avatar answered Sep 27 '22 21:09

Tim Cooper


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

$time = '21:30:10'; $seconds = strtotime("1970-01-01 $time UTC"); echo $seconds;  // same with objects (for php5.3+) $time = '21:30:10'; $dt = new DateTime("1970-01-01 $time", new DateTimeZone('UTC')); $seconds = (int)$dt->getTimestamp(); 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


If you will parse format MM:SS with strtotime() or date_parse() it will fail (date_parse() is used in strtotime() and DateTime), because when you input format like xx:yy parser assumes it is HH:MM and not MM:SS. I would suggest checking format, and prepend 00: if you only have MM:SS.

demo strtotime() demo date_parse()


If you have hours more than 24, then you can use next function (it will work for MM:SS and HH:MM:SS format):

function TimeToSec($time) {     $sec = 0;     foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v;     return $sec; } 

demo

like image 35
Glavić Avatar answered Sep 27 '22 19:09

Glavić