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

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.

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;

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

$time = 00:06:00;
$timeInSeconds = strtotime($time) - strtotime('TODAY');

You can use the strtotime function to return the number of seconds from today 00:00:00.
$seconds= strtotime($time) - strtotime('00:00:00');

In pseudocode:
split it by colon
seconds = 3600 * HH + 60 * MM + SS

Try this:
$time = "21:30:10";
$timeArr = array_reverse(explode(":", $time));
$seconds = 0;
foreach ($timeArr as $key => $value)
{
if ($key > 2) break;
$seconds += pow(60, $key) * $value;
}
echo $seconds;

Simple
function timeToSeconds($time)
{
$timeExploded = explode(':', $time);
if (isset($timeExploded[2])) {
return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
}
return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}

function time2sec($time) {
$durations = array_reverse(explode(':', $item->duration));
$second = array_shift($durations);
foreach ($durations as $duration) {
$second += (60 * $duration);
}
return $second;
}
echo time2sec('4:52'); // 292
echo time2sec('2:01:42'); // 7302

On Windows 32 bit PHP version: 7.2.31 i get some error on all versions posted here.
If the time was 00:00:00 or 00:00:00 the zeros 00 were returned and used as "" empty string, and calculation with empty string returns error "A Non WELLNUMERIC blabla.
This Works also with more then 24hours:
function TimeToSec(string $time) {
$timearray = explode(":",$time);
$hours = (int)$timearray[0];
$minutes = (int)$timearray[1];
$seconds = (int)$timearray[2];;
//echo "Hours: " . $hours ."<br>";
//echo "minutes: " . $minutes ."<br>";
//echo "seconds: " . $seconds ."<br>";
$value = ($hours * 3600) + ($minutes * 60) + $seconds;
return $value;
}
echo TimeToSec("25:00:30");

<?php
$time = '21:32:32';
$seconds = 0;
$parts = explode(':', $time);
if (count($parts) > 2) {
$seconds += $parts[0] * 3600;
}
$seconds += $parts[1] * 60;
$seconds += $parts[2];

Related

How to sum two times with milliseconds?

Is there any way to sum two times with milliseconds like this:
00:01:02.73
00:03:03.01
to one?
the result should be like this:
00:04:05.74
format is simple "hours:minutes:seconds.milliseconds"
If yes, how?
well I wrote few functions which is helping me to do that
$time1 = "00:15:45.89";
$time2 = "00:18:30.22";
$milli1 = timeToMilliseconds($time1);
$milli2 = timeToMilliseconds($time2);
$new = $milli1 + $milli2;
$time = formatMilliseconds($new);
echo $time;
function timeToMilliseconds($time){
$time_start = substr($time, -11, -3);
$time_end = substr($time, -3);
$time_arr = explode(':', $time_start);
$seconds = 0;
foreach($time_arr as $key => $val){
if($key == 0){
$seconds += $val * 60 * 60;
}elseif($key == 1){
$seconds += $val * 60;
}elseif($key == 2){
$seconds += $val;
}
}
$seconds = $seconds.$time_end;
$milliseconds = $seconds * 1000;
return $milliseconds;
}
function formatMilliseconds($milliseconds) {
$seconds = floor($milliseconds / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$milliseconds = $milliseconds % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
$format = '%u:%02u:%02u.%03u';
$time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
return rtrim($time, '0');
}
Has a problem with your solution #Scorpioniz, when the time is "1:34:55.831" for example, the return from formatMilliseconds is "1582:10:31.704".
I made some changes in the timeToMilliseconds function and I think that is more consistent:
function timeToMilliseconds($time){
$dateTime = new DateTime($time);
$seconds = 0;
$seconds += $dateTime->format('H') * 3600;
$seconds += $dateTime->format('i') * 60;
$seconds += $dateTime->format('s');
$seconds = floatval($seconds . '.' . $dateTime->format('u'));
return $seconds * 1000;
}
Or if your version of PHP is minor than 5.2.2 then you can do:
function timeToMilliseconds($time){
sscanf($time, "%d:%d:%d.%d", $hours, $minutes, $seconds, $microseconds);
$seconds += $hours * 3600;
$seconds += $minutes * 60;
$seconds = floatval($seconds . '.' . $microseconds);
return $seconds * 1000;
}
I hope someone enjoy.
(Sorry for my English if I said something strange :P)
I've found this, it has less code than yours and it does the job. I've added function for milliseconds.
I'm wondering if php has something built-in for this.
/**
* #author Masino Sinaga, http://www.openscriptsolution.com
* #copyright October 13, 2009
*/
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
$Imiliseconds = 0.0;
foreach ($times as $time){
list($rest, $miliseconds) = explode('.', $time);
$Imiliseconds += '0.'.$miliseconds;
list($hour, $minute, $second) = explode(':', $rest);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$seconds += floor($Imiliseconds);
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
$miliseconds = $Imiliseconds-floor($Imiliseconds);
// return "{$hours}:{$minutes}:{$seconds}:{$miliseconds}";
return sprintf('%02d:%02d:%02d:%02d', $hours, $minutes, $seconds, $miliseconds); // Thanks to Patrick
}
echo sum_the_time($time, $time2); // this will give you a result: 19:12:25

Turning minutes into hours if necessary in php

I tried this:
$total_time_minutes = '132';
$total_time_hours = '26';
if($total_time_minutes > 60)
{
$time = strtotime( $minutes . ' minutes');
$time = date('H:i', $time);
$time = explode(':', $time);
$hours = $time[0];
$minutes = $time[1];
$total_time_hours += $hours;
$total_time_minutes = $minutes;
}
if i output $total_time_hours and $total_time_minutes from this it will give me: 26:44, which is incorrect.
It should give me 28:12, what's wrong here?
$total_time_minutes = '132';
$total_time_hours = '26';
if($total_time_minutes > 60)
{
$hours = floor($total_time_minutes / 60);
$minutes = $total_time_minutes % 60;
$total_time_hours += $hours;
$total_time_minutes = $minutes;
}
date() function if for unix timestamp formatting. What you have is not a valid unix timestamp (yes, I understand it could be that small, but not in this particular case)

adding two time values of similar formats using php

i have two time values as give below
$time = 06:58:00;
$time2 = 00:40:00;
I am doing this for calculating the appointments and available time for a particular user
so i tried in this way
$max_date=abs(strtotime($time) + strtotime($time2));
but it is returning $max_date =2673452280
any suggestions pls
this code sample would take hour in $time and add the hour in $time2 to it
for example: time=06:58:00, time2=00:40:00, result = 07:38:00
$time = "06:58:00";
$time2 = "00:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
Use this function...
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
strtotime function takes full-date as an argument and valid format are as following:
http://www.php.net/manual/en/datetime.formats.php
You can see that in online PHP manual for the function at http://php.net/manual/en/function.strtotime.php
If you're build those time strings from a database before, you'd probably want to rebuild them to something like this:
$time = "00:06:58";
$time2 = "40 minutes";
$timestamp = strtotime($time." +".$time2);
$endTime = date("d.m.Y H:i:s", $timestamp);
Easiest way to add two times using php is :
1) Convert time from H:i:s (e.g. 08:15:40) format to seconds.
2) do the same for second time value ref:step 1
3) add converted values and store it php variable
4) Now convert total (which is in seconds) to H:i:s
and it works for me.
PHP Script:
$str_time ="08:04:40";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_old_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$str_time ="02:10:22";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_toadd_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$hrs_old_int1 = $hrs_old_seconds + $hrs_toadd_seconds;
echo $Total=gmdate("H:i:s", $hrs_old_int1);
Result= :10:15:02
Anudeep's solution was great for my use case, but I needed to be able to add negative times as well. Here's a slightly edited version of his code to take and return negative time strings ("-01:01:01" for example):
public static function sum_the_times($time1, $time2)
{
$times = array($time1, $time2);
$seconds = 0;
$negative = false;
foreach ($times as $time) {
list($hour,$minute,$second) = explode(':', $time);
if(substr($hour,0,1) == '-'){
$seconds -= substr($hour,1)*3600;
$seconds -= $minute*60;
$seconds -= $second;
} else {
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
}
if (substr($seconds, 0, 1) == '-') {
$negative = true;
$seconds = ($seconds * -1);
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if ($seconds < 9) {
$seconds = "0".$seconds;
}
if ($minutes < 9) {
$minutes = "0".$minutes;
}
if ($hours < 9) {
$hours = "0".$hours;
}
return ($negative ? "-" : "")."{$hours}:{$minutes}:{$seconds}";
}
You can try this
$time = "04:00:00";
$time2 = "03:30:00";
$result = date("H:i:s",strtotime($time)+strtotime($time2));
echo $result;
It gives output 07:30:00 but it does not work sometime in different version of operating system. If you want to get sum of time then you can use this code
<?php
function CalculateTime($time1, $time2) {
$time1 = date('H:i:s',strtotime($time1));
$time2 = date('H:i:s',strtotime($time2));
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
$time1= '23:32:05';
$time2 = '01:29';
echo CalculateTime($time1,$time2);
?>
In the second code, you can send time in hour:minutes or hours:minutes:seconds. This code accept both format because it convert time automatically
Here's a version that will cater for over 24 hours and doesn't use strtotime:
$time0 = "24:01:02";
$time1 = "01:02:03";
$matches0 = explode(':',$time0); // split up the string
$matches1 = explode(':',$time1);
$sec0 = $matches0[0]*60*60+$matches0[1]*60+$matches0[2];
$sec1 = $sec0+ $matches1[0]*3600+$matches1[1]*60+$matches1[2]; // get total seconds
$h = intval(($sec1)/3600);
$m = intval(($sec1-$h*3600)/60);
$s = $sec1-$h*3600-$m*60;
echo $str = str_pad($h, 2, '0', STR_PAD_LEFT).':'.str_pad($m, 2, '0', STR_PAD_LEFT).':'.str_pad($s, 2, '0', STR_PAD_LEFT);

Convert mm:ss to Milliseconds in PHP

Can you please let me know how to convert mm:ss to milliseconds in PHP.
$value = "10:10"
$ms = ...
No need to do string conversions or array manipulations:
sscanf($value, "%d:%d", $minutes, $seconds);
$ms = $seconds * 1000 + $minutes * 60 * 1000;
$ms = intval(substr($value, 0, 2))*60*1000 + intval(substr($value, 2, 2))*1000;
$value = "10:10";
$time = explode(':',$value);
$ms = $time[0]*60000 + $time[1]*1000;
$value = "10:10";
list($minutes, $seconds) = explode(':', $value);
$milliseconds = $seconds * 1000 + $minutes * 60000;
var_dump($milliseconds); // 610000

Output is in seconds. convert to hh:mm:ss format in php

My output is in the format of 290.52262423327 seconds. How can i change this to 00:04:51?
The same output i want to show in seconds and in HH:MM:SS format, so if it is seconds, i want to show only 290.52 seconds.(only two integers after decimal point)? how can i do this?
I am working in php and the output is present in $time variable. want to change this $time into $newtime with HH:MM:SS and $newsec as 290.52.
Thanks :)
1)
function foo($seconds) {
$t = round($seconds);
return sprintf('%02d:%02d:%02d', ($t/3600),($t/60%60), $t%60);
}
echo foo('290.52262423327'), "\n";
echo foo('9290.52262423327'), "\n";
echo foo(86400+120+6), "\n";
prints
00:04:51
02:34:51
24:02:06
2)
echo round($time, 2);
Try this one
echo gmdate("H:i:s", 90);
For till 23:59:59 hours you can use PHP default function
echo gmdate("H:i:s", 86399);
Which will only return the result till 23:59:59
If your seconds is more then 86399 than
with the help of #VolkerK answer
$time = round($seconds);
echo sprintf('%02d:%02d:%02d', ($time/3600),($time/60%60), $time%60);
will be the best options to use ...
Edit: A comment pointed out that the previous answer fails if the number of seconds exceeds a day (86400 seconds). Here's an updated version. The OP did not specify this requirement so this may be implemented differently than the OP might expect, and there may be much better answers here already. I just couldn't stand having provided an answer with this bug.
$iSecondsIn = 290.52262423327;
// Account for days.
$iDaysOut = 0;
while ($iSecondsIn >= 86400) {
$iDaysOut += 1;
$iSecondsIn -= 86400;
}
// Display number of days if appropriate.
if ($iDaysOut > 0) {
print $iDaysOut.' days and ';
}
// Print the final product.
print date('H:i:s', mktime(0, 0, $iSecondsIn));
The old version, with the bug:
$iSeconds = 290.52262423327;
print date('H:i:s', mktime(0, 0, $iSeconds));
Try this:
$time = 290.52262423327;
echo date("h:i:s", mktime(0,0, round($time) % (24*3600)));
Based on https://stackoverflow.com/a/3534705/4342230, but adding days:
function durationToString($seconds) {
$time = round($seconds);
return sprintf(
'%02dD:%02dH:%02dM:%02dS',
$time / 86400,
($time / 3600) % 24,
($time / 60) % 60,
$time % 60
);
}
I dont know if this is the most efficient way, but if you also need to display days, this works:
function foo($seconds) {
$t = round($seconds);
return sprintf('%02d %02d:%02d:%02d', ($t/86400%24), ($t/3600) -(($t/86400%24)*24),($t/60%60), $t%60);
}
Try this :)
private function conversionTempsEnHms($tempsEnSecondes)
{
$h = floor($tempsEnSecondes / 3600);
$reste_secondes = $tempsEnSecondes - $h * 3600;
$m = floor($reste_secondes / 60);
$reste_secondes = $reste_secondes - $m * 60;
$s = round($reste_secondes, 3);
$s = number_format($s, 3, '.', '');
$h = str_pad($h, 2, '0', STR_PAD_LEFT);
$m = str_pad($m, 2, '0', STR_PAD_LEFT);
$s = str_pad($s, 6, '0', STR_PAD_LEFT);
$temps = $h . ":" . $m . ":" . $s;
return $temps;
}
Personally, going off other peoples answers I made my own parser.
Works with days, hours, minutes and seconds. And should be easy to expand to weeks/months etc.
It works with deserialisation to c# as well
function secondsToTimeInterval($seconds) {
$t = round($seconds);
$days = floor($t/86400);
$day_sec = $days*86400;
$hours = floor( ($t-$day_sec) / (60 * 60) );
$hour_sec = $hours*3600;
$minutes = floor((($t-$day_sec)-$hour_sec)/60);
$min_sec = $minutes*60;
$sec = (($t-$day_sec)-$hour_sec)-$min_sec;
return sprintf('%02d:%02d:%02d:%02d', $days, $hours, $minutes, $sec);
}
1)
$newtime = sprintf( "%02d:%02d:%02d", $time / 3600, $time / 60 % 60, $time % 60 );
2)
$newsec = sprintf( "%.2f", $time );
If you're using Carbon (such as in Laravel), you can do this:
$timeFormatted = \Carbon\Carbon::now()->startOfDay()->addSeconds($seconds)->toTimeString();
But $timeFormatted = date("H:i:s", $seconds); is probably good enough.
Just see caveats.
Here was my implementation with microseconds
/**
* #example 00 d 00 h 00 min 00 sec 005098 ms (0.005098 sec.ms)
*/
public function __toString()
{
// Add your code to get $seconds and $microseconds
$time = round(($seconds + $microseconds), 6, PHP_ROUND_HALF_UP);
return sprintf(
'%02d d %02d h %02d min %02d sec %06d ms (%s sec.ms)',
$time / 86400,
($time / 3600) % 24,
($time / 60) % 60,
$time % 60,
$time * 1000000 % 1000000,
$time
);
}
echo date('H:i:s', round($time)%86400);
Simple formatter with progressively added parts - sample:
formatTime(123) => 2m 3s
formatTime(7400) => 2h 3m 20s
formatTime(999999) => 11d 13h 46m 39s
function formatTime($secs)
{
$secs = max(0, intval($secs));
if($secs > 0){
$out = [];
$yrs = floor($secs / 31536e3);
if($yrs){
$out[] = $yrs."y";
}
$rem = $secs - $yrs * 31536e3;
$days = floor($rem / 86400);
if($days || $out){
$out[] = $days."d";
}
$rem -= $days * 86400;
$hrs = floor($rem / 3600);
if($hrs || $out){
$out[] = $hrs."h";
}
$rem -= $hrs * 3600;
$min = floor($rem / 60);
if($min || $out){
$out[] = $min."m";
}
$rem -= $min * 60;
$out[] = $rem."s";
return implode(" ", $out);
}
return 0;
}
echo date('H:i:s',$time);
echo number_format($time,2);
Numero uno... http://www.ckorp.net/sec2time.php (use this function)
Numero duo... echo round(290.52262423327,2);

Categories