How to sum two times with milliseconds? - php

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

Related

Implementing cost in time calculations. How?

I have the following function that adds the times contained in an array. It doesn't return the pay out. I would like to return the totalTime AND the totalPayOut.
Like so:
function sumTimesInArray($times = []) {
$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;
return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
}
$times = ["01:00:00","00:15:00","00:00:30",]; // = 01:15:30 hours
$pay = 10;
$totalTime = sumTimesInArray($times);
print($totalTime);
Given a pay of $10/hour, how would I implement this so that it includes the prorated pay for fractional hours? Currently working on it.
this is the code i have tried, you can try
Syntax PHP
<?php
function sumTimesInArray($pay, $times) {
$dataPayouts = array();
$payoutTotal = 0;
$totalSeconds = 0; // not reset
foreach ($times as $time) {
list($hour, $minute, $second) = explode(":", $time);
$seconds = 0; // reset
$seconds += $hour * 3600;
$seconds += $minute * 60;
$seconds += $second;
$totalSeconds += $seconds;
$itemPayout = ($pay / 3600) * $seconds;
$dataPayouts[] = array(
'time' => $time,
'pay_per_hour' => $pay,
'item_payout' => $itemPayout
);
$payoutTotal += $itemPayout;
}
$hours = floor($seconds / 3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds / 60);
$seconds -= $minutes * 60;
$resume = array(
'hour_total' => gmdate("H:i:s", $totalSeconds),
'payout_total' => $payoutTotal,
'details' => $dataPayouts
);
return $resume;
}
$times = array("01:00:00","00:15:00","00:00:30",); // = 01:15:30 hours
$pay = 10;
echo json_encode(sumTimesInArray($pay, $times));
Result JSON
{
"hour_total": "01:15:30",
"payout_total": 12.583333333333,
"details": [
{
"time": "01:00:00",
"pay_per_hour": 10,
"item_payout": 10
},
{
"time": "00:15:00",
"pay_per_hour": 10,
"item_payout": 2.5
},
{
"time": "00:00:30",
"pay_per_hour": 10,
"item_payout": 0.083333333333333
}
]
}
Demo code : http://codepad.org/z9x3Hsna
You should have a look at the DateTime and DateIntervall class (Doc). It can sum times and parse them for you, so you do not have to do it yourself.
But you can also easy modify your code:
function sumTimesAndCalcPay($times = [], $payPerHour = 1) {
$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;
$time = sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
$pay = $payPerHour * ($hours + $minutes/60 + $seconds/3600);
return [$time, $pay];
}
$times = ["01:00:00","00:15:00","00:00:30",]; // = 01:15:30 hours
$pay = 10;
[$totalTime, $totalPay] = sumTimesAndCalcPay($times, $pay);
print($totalTime);
print($totalPay);

Sum two centesimal times

I found this code but there is an error I can't found
function sum_time($tempo1, $tempo2) {
$times = array($tempo1, $tempo2);
$seconds = 0;
foreach ($times as $tempo)
{
list($hour, $minute, $second) = explode('.', $tempo);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
// return "{$hours}:{$minutes}:{$seconds}";
return sprintf('%02d.%02d.%02d', $hours, $minutes, $seconds);
}
echo sum_time('3.0.00', '4.83.00');
the result is 08.23.00 instead of 7.83.00
Probably the problem is the code sums times in hh.mm.ss while I want to sum tims in hh.cc (hours.cents)
You can convert it to not use seconds but cents like this,
<?php
function sum_time($tempo1, $tempo2) {
$times = array($tempo1, $tempo2);
$hours = 0;
$cents = 0;
foreach ($times as $tempo)
{
list($hour, $cent) = explode('.', $tempo);
$hours += $hour;
$cents += $cent;
}
$hours += floor($cents / 100);
$cents = $cents % 100;
// return "{$hours}:{$cents}";
return sprintf('%02d.%02d', $hours, $cents);
}
echo sum_time('3.0', '4.83');

A negative number is converted too negative

<?php
function convertToHoursMins($total, $format = '%02d:%02d') {
$hours = intval($total / 60);
$minutes = ($total % 60);
return sprintf($format, $hours, $minutes);
}
echo convertToHoursMins($total, $format = '%02d:%02d');
?>
This solution works perfect (like many other solutions) when $total is positive.
When $total on the other hand is negative both $hours and $minutes gets negative like -hours:-minutes.
Every solution I have tried echoes the same output, and I am getting frustrated.
I really wood appreciate some help!
One of solutions is to work with absolute value of $total and prepend - if required:
function convertToHoursMins($total, $format = '%02d:%02d')
{
$absTotal = abs($total);
$hours = intval($absTotal / 60);
$minutes = ($absTotal % 60);
return sprintf((0 <= $total ? '' : '-') . $format, $hours, $minutes);
}
function convertToHoursMins($total, $format = '%02d:%02d') {
$total = abs($total);
$hours = intval($total / 60);
$minutes = ($total % 60);
return sprintf($format, $hours, $minutes);
}

Get total amount of hours from 2 variables

Here is my code:
$time = "20:58:05";
$time2 = "10:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
echo $result;
The output of the above code is - 07:38:05
i want it to display like this - 31:38:05. How can i achieve this?
Convert both times to seconds, add them, and then calculate the hours, minutes, and seconds yourself.
$time = "20:58:05";
$time2 = "10:40:00";
$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);
The solution of Barmar works when adding hours that are below 24:00:00, but when you add 2 variable with each variable exceeds 24:00:00 it gives a wrong output. For example:
$time = "20:58:05";
$time2 = "30:40:00";
$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);
output of the above code: -431348:-2:-55
Here is a code that works even if the data of the variables exceeds 24:00:00:
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}";
}
i found this code here

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

Categories