I want to add up time in php but after hours of google'ing and trying out im still unable to find a solution.
my values are:
$newTotal = '00:45:00';
$oldTotal = '00:16:00';
I want to add those two up which make 01:01:00.
Can you give me an example i'm getting really desperate! :p
thanks in advance,
Use strtotime() to turn them into Unix timestamps, then add them as integers:
$newTotal = '00:45:00';
$oldTotal = '00:16:00';
$total = strtotime($newTotal) + strtotime($oldTotal);
To format it as hh:mm:ss again, use date():
echo date('H:i:s', $total);
This gives:
01:01:00
If these values always look like that, you could break them down with a substr()
$hours1 = substr($newTotal, 0, 2);
etc. And then simply add up the seconds, do a divide and mod and bubble up to the hours, and voila!
$secondstotal = $seconds1+$seconds2;
$restseconds = $secondstotal % 60;
$minutesfromseconds = floor($restseconds / 60);
$minutestotal = $minutes1+$minutes2+$minutesfromseconds;
etc.
keep a start date for minimum error.
<?php
$origin = '00:00:00';
$newTotal = '00:45:00';
$oldTotal = '00:16:00';
$added = strtotime($newTotal) + (strtotime($oldTotal) - strtotime($origin));
echo date('H:i:s', $added );
output :
01:01:00
Note, if your time is more than 23:59:59 after adding, you will get wrong result.
Another solution without time function:
function sumtotal($a,$b) {
$i = explode(':',$a);
$j = explode(':',$b); // 0hh:1mm:2ss
$k = array(0,0,0,0); // 0days:1hours:2minutes:3seconds
$k[3] = $i[2]+$j[2];
$k[2] = (int)($k[3]/60)+$i[1]+$j[1];
$k[1] = (int)($k[2]/60)+$i[0]+$j[0];
$k[0] = (int)($k[1]/24);
$k[3] %= 60;
$k[2] %= 60;
$k[1] %= 24;
if ($k[3]<10) $k[3] = '0'.$k[3];
if ($k[2]<10) $k[2] = '0'.$k[2];
if ($k[1]<10) $k[1] = '0'.$k[1];
return $k[0].' days : '.$k[1].' hours : '.$k[2].' minutes : '.$k[3].' seconds';
}
$newTotal = '01:45:21';
$oldTotal = '03:16:56';
echo sumtotal($newTotal,$oldTotal); // result: 0 days : 05 hours : 02 minutes : 17 seconds
Related
I want to convert two integer as a time like:
$hour = 13;
$minute = 45;
---> $result = 13:45:00 //(In TimeFormart)
after I combine that i have to do some SQL Querys and PHP Calculations
can somebody help me?
Even when your question is very difficult to understand. Nobody knows what exactly you want to do and in which way and volume.
The only correct way to do it is this way:
$hour = 13;
$minute = 45;
$seconds = 0;
$result = date('H:i:s', mktime($hour, $minute, $seconds));
echo $result;
// output: 13:45:00
Important: When using it for making a time, you must pass hour, minute, seconds - if you dont pass seconds it takes the current time seconds.
You can even pass day, month, year for more information check out the PHP Reference.
https://www.php.net/manual/de/function.mktime.php
Try this code may be it help you.
<?php
$hour = 13;
$minute = 45;
$second=35;
// $result = 13:45:00 //(In TimeFormart)
$result = $hour.":".$minute.":".$second;
echo $result;
?>
here's what you want, but if you put more than 24 in hour, it'll accept, it just returns you how many hours, minutes and seconds not that actual time
$hour = 13;
$minute = 45;
echo date($hour.':'.$minute.':s');
$hour = 13;
$minute = 45;
$result = $hour . ':' . $minute . ':' . '00';
echo $result;
output---> 13:45:00 //(In TimeFormart)
i have two different break time
default break time
extra break time
here i want to sum of two times and display 12 hrs format
EX :
$default_time = "00:30";
$extra_time = "00:25";
my expected output : 00:55
but now display 01:00
this is my code
$default_time = $work_data->break_time;
$break_time = $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
Here is the function you can calculate total time by passing the arguments to functions.
$hours, $min are supposed variable which is zero
$default_time = "00:30";
$break_time = "00:25";
function calculate_total_time() {
$i = 0;
foreach(func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if( $h = floor($i / 60) ) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo calculate_total_time($default_time, $break_time); # 00:55
There is one function call to strtotime function too much.
You should leave out the strtotime() call in the last line, as $total_break already is a UNIX timestamp:
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);
The problem is that you're trying to add too specific timestamps, but what you're trying to achieve is adding two durations. So you need to convert those timestamps into durations. For that you need a base, which in your case is 00:00.
$base = strtotime("00:00");
$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds
$break_time = $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds
$total_break = $default_duration + $break_duration; // 55 min in seconds
// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);
Consider using standard DateTime and DateInterval classes. All you will need is to convert your second variable value to interval_spec format (see http://php.net/manual/en/dateinterval.construct.php for details):
$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'
$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');
You could try the following code fragment:
$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime / 60) . ":" . ($fulltime % 60);
<?php
$time = "00:30";
$time2 = "00:25";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
print_r($result);
?>
Use below code you will definitely get your answers.
$default_time = "00:30:00";
$extra_time = "00:25:00";
$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;
You can modify above code as per your need.
You could try the following:
$default_time = $work_data->break_time;
$date_start = new DateTime($default_time);
$break_time = $work_data->extra_time;
$interval = new DateInterval("PT" . str_replace(":", "H", $break_time) . "M");
$date_end = $date_start->add($interval);
echo $date_end->format("H:i");
Note that this doesn't account for times which span a 24 hour period
I'm looking for a posibility to set minutes to "00" instead of "60". I have following code:
$minute = date('i');
$minutesround = round($minute / 10) * 10;
$hour = date('H');
$minutesround = str_pad($minutesround, 2, 0, STR_PAD_LEFT);
$time = $hour . $minutesround;
echo $time;
My problem: If it is eg. 4:56pm the output should like this: 1700
but in my case, I get this 1660
Someone has an idea, how to realize this?
Thank you!
This works well:
$myRoundedTime = round(time()/600) * 600; // round time to nearest 6th of an hour
$time = date('Hi', $myRoundedTime);
echo $time;
A working example: http://sandbox.onlinephpfunctions.com/code/b2b595683d9adf8e5273cbdef775bf69b6c036d4
A simple if statement should do the trick
$hour = date('H');
if($minutesround == 60) {
$minutesround = 0;
$hour++;
if($hour == 24) $hour = '00';
}
I have a time average total that is computed from a time converted from an integer.
average = 0:0:20
I wanted to change its output like this:
average = 00:00:20
By the way, this is the code I used to get the time average:
$ans = $times / $displaycount;
$hh = floor($ans / 3600);
$mm = floor(($ans - ($hours*3600)) / 60);
$ss = floor($ans % 60);
$timeavg = $hh.':'.$mm.':'.$ss;
echo "average = ". $timeavg;
try
$str= '0:0:20';
echo date('H:i:s', strtotime($str)); //output :- 00:00:20
I would recommend to use format function like sprintf():
$timeavg = sprintf('%02d:%02d:%02d', $hh, $mm, $ss);
demo
I can't wrap my brain around this one so I hope someone can help. I have a song track that has the song length in milliseconds. I also have the date the song played in DATETIME format. What I am trying to do is find out how many milliseconds is left in the song play time.
Example
$tracktime = 219238;
$dateplayed = '2011-01-17 11:01:44';
$starttime = strtotime($dateplayed);
I am using the following to determine time left but it does not seem correct.
$curtime = time();
$timeleft = $starttime+round($tracktime/1000)-$curtime;
Any help would be greatly appreciated.
For my needs I used the following approach:
$curTime = microtime(true);
// something time consuming here
...
// get time difference in milliseconds
$timeConsumed = round(microtime(true) - $curTime,3)*1000;
So, the point is that we use float representation of time here (see http://php.net/manual/en/function.microtime.php)
Hope you will adopt it for your needs.
i use the following set of functions for handling mysql dates, maybe they can help you:
function sqlArray($date, $trim=true) {
$result = array();
$result['day'] = ($trim==true) ? ltrim(substr($date,8,2),'0') : substr($date,8,2);
$result['month'] = ($trim==true) ? ltrim(substr($date,5,2),'0') : substr($date,5,2);
$result['year'] = substr($date,0,4);
$result['hour'] = substr($date,11,2);
$result['minutes'] = substr($date,14,2);
return $result;
}
function sqlInt($date) {
$date = sqlArray($date);
return mktime($date['hour'], $date['minutes'], 0, $date['month'], $date['day'], $date['year']);
}
function difference($dateStart, $dateEnd) {
$start = sqlInt($dateStart);
$end = sqlInt($dateEnd);
$difference = $end - $start;
$result = array();
$result['ms'] = $difference;
$result['hours'] = $difference/3600;
$result['minutes'] = $difference/60;
$result['days'] = $difference/86400;
return $result;
}
in your case it should be something like:
$dateplayed = '2011-01-17 11:01:44';
print_r(difference($dateplayed, date('Y:m:d')));
hope it works :D
I have written this function to calculate duration between given two timestamps (with milliseconds).
function calculateTransactionDuration($startDate, $endDate)
{
$startDateFormat = new DateTime($startDate);
$EndDateFormat = new DateTime($endDate);
// the difference through one million to get micro seconds
$uDiff = ($startDateFormat->format('u') - $EndDateFormat->format('u')) / (1000 * 1000);
$diff = $startDateFormat->diff($EndDateFormat);
$s = (int) $diff->format('%s') - $uDiff;
$i = (int) ($diff->format('%i')) * 60; // convert minutes into seconds
$h = (int) ($diff->format('%h')) * 60 * 60; // convert hours into seconds
return sprintf('%.6f', abs($h + $i + $s)); // return total duration in seconds
}
$startDate = '02-Mar-16 07.22.13.000548';
$endDate = '02-Mar-16 07.22.14.000072';
$difference = calculateTransactionDuration($startDate, $endDate);
//Outputs 0.999524 seconds
You could convert the datetime string/input into unixtimestamp and then get the difference. If you do have milliseconds, unixtimestamp would have digits after the decimal. Once you have the difference, you can convert that value back into your date time pattern using function date in php. Below is the link.
Good luck!
http://php.net/manual/en/function.date.php
I used this function for my self:
public function calculateStringTimeToMiliseconds($timeInString)
{
$startTime = new \DateTime("now");
$endDate = new \DateTime($timeInString);
$interval = $startTime->diff($endDate);
$totalMiliseconds = 0;
$totalMiliseconds += $interval->m * 2630000000;
$totalMiliseconds += $interval->d * 86400000;
$totalMiliseconds += $interval->h * 3600000;
$totalMiliseconds += $interval->i * 60000;
$totalMiliseconds += $interval->s * 1000;
return $totalMiliseconds;
}