This question already has answers here:
How to get time difference in minutes in PHP
(21 answers)
Closed 5 years ago.
I have to find the total working time of a staff.
Variables in my hand is,
$work_time_start = "8:00:00";
$work_time_end = "18:00:00";
$lunch_break_start = "13:00:00";
$lunch_break_end = "14:00:00";
From this I have to find the total working time of a staff.
For example.
//example 1
$work_start_time = "14:00:00";
$work_end_time = "14:25:00";
//The output should be: 00:25:00
//example 2
$work_start_time = "14:00:00";
$work_end_time = "10:25:00";
//The output should be: 06:25:00
How to achieve the required output. I have no idea.
Detailed answer as requested.
$work_time_start = "8:00:00";
$work_time_end = "18:00:00";
$lunch_break_start = "13:00:00";
$lunch_break_end = "14:00:00";
$worktime = convert_to_seconds($work_time_end) - convert_to_seconds($work_time_start);
$lunchtime = convert_to_seconds($lunch_break_end) - convert_to_seconds($lunch_break_start);
$worktime = $worktime - $lunchtime;
echo $worktime;
function convert_to_seconds($str_time)
{
$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;
return $time_seconds;
}
Hope this helps
$work_start_time =new DateTime("14:00:00");
$work_end_time = new DateTime("14:25:00");
$interval = $work_end_time->diff($work_start_time);
echo $interval->format('%H:%I:%S');
Use the following code:
$work_time_start = "8:00:00";
$work_time_end = "18:00:00";
$lunch_break_start = "13:00:00";
$lunch_break_end = "14:00:00";
$total_time = strtotime($lunch_break_start) - strtotime($work_time_start) + strtotime($work_time_end) - strtotime($lunch_break_end);
echo date("h:i:s", mktime(0,0, round($total_time) % (24*3600)));
Related
This question already has answers here:
How to get millisecond between two dateTime obj?
(5 answers)
Closed 3 years ago.
How to get a range between two dates in a millisecond :
I have an example of the correct answer:
time_start = 2018-12-18 12:33:53.1231;
time_end = 2018-12-18 12:34:10.1523;
result = 17.0292;
what I'm asking is, what is the formula for calculating it?
I have tried some code but the result is 16.708
$dt_start = 2018-12-18 12:33:53.1231;
$dt_end = 2018-12-18 12:34:10.1523;
$ex_start = explode(".",$dt_start);
$ex_end = explode(".",$dt_end);
$datetime_start = strtotime($ex_start[0]);
$datetime_end = strtotime($ex_end[0]);
$total_detik = $datetime_end-$datetime_start;
// dd($ex_end[0]);
$milis_start = floatval($ex_start[1]);
$milis_end = floatval($ex_end[1]);
$range_milis = $milis_start-$milis_end;
$new_range_milis = $range_milis/10000;
// dd($range_milis);
$second = $datetime_end-$datetime_start+$range_milis/10000;
dd($second);
//output '16.708'
Try this to find the difference between two time.
<?php
function calculateTransactionDuration($startDate, $endDate)
{
$startDateFormat = new DateTime($startDate);
$EndDateFormat = new DateTime($endDate);
$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;
$h = (int) ($diff->format('%h')) * 60 * 60;
return sprintf('%.6f', abs($h + $i + $s));
}
$time_start = '2018-12-18 12:33:53.1231';
$time_end = '2018-12-18 12:34:10.1523';
echo $difference = calculateTransactionDuration($time_start, $time_end);
// output = 17.029200
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 have lets say a $value = 5; and the valnue means 5 minutes, and i have a file saved on the server and getting modified a lot called check.txt i want a code to do a calculation of if timenow - timemodification of file <= 0 in H:i:s from the main $value of 5 minutes then continue, else echo please wait minutes left from the time now - filetimemodification of the main value of 5 minutes = $timeleft in m:s format.
i'm testing on the current code but i keep getting a value of -1376352747
my code which is know is bad :) is
$filename = 'check.txt';
$time = date("H:i:s");
$time = str_replace("00", "24", $time);
$filemodtime = filemtime($filename);
$timeleft = $time - $filemodtime;
$h = explode(':', $time);
$h = $h[0];
$h = str_replace("00", "24", $h);
$m = explode(':', $time);
$m = $m[1];
$s = explode(':', $time);
$s = $s[2];
$hms = ("$h:$m:$s");
if (count($filemodtime - $time) <= 0) {
echo "you can continue";
}
else {
echo " please wait $timeleft";
}
thanks in advance
The filemtime() function returns a UNIX-timestamp in seconds, and the time() function returns the current time as a UNIX-timestamp. So by using that difference, you get the file's age in seconds.
$age = time() - filemtime($filename);
// if older then 5 minutes (5 * 60 secounds)
if($age > $value*60)
{
// good
}
else
{
$time_left = $value * 60 - $age;
$time_left_secounds = $time_left % 60;
$time_left_minutes = ($time_left - $time_left_secounds) / 60;
$formated_time_left = sprintf("%02d:%02d", $time_left_minutes, $time_left_secounds);
echo "Please wait {$formated_time_left}";
}
I would recommend to work with time() rather than date().
that way, you can substract the file time from the current time() function, and see if it is bigger than 5 minutes * 60 seconds.
Good luck!
I have a big problem for getting/computing the minutes.
Scenario:
I have a form which is the user can input the seconds [5s, 10s, 25s, 30s, 60s]. I called the table "Duration"
I already have "Duration" [compose of minutes:seconds], in my database which is "1:5" [the last input]. Then I insert again another seconds "10s"...
*the format is minutes:seconds
The correct output should be: 1:15
The current result is : 0:15
AS we see. I have a problem in computing the minutes. The codes I will show is good for subtracting the seconds. But now I need to revised it to adding the seconds.
Here's my code:
$duration = $_POST["duration"];
if(sizeof($bldg) == 1)
{
$total = sizeof($bldg)-1;
}
else
{
$total = sizeof($bldg)%2;
}
for($i=0; $i<sizeof($bldg);$i++)
{
$result = mysql_query("SELECT fldTotalDuration FROM tbldata WHERE fldNetname = '".$network."' AND fldBldgName = '".$bldg[$i]."' AND fldWeek = '".$week."' AND fldMonth = '".$month."' ");
if(mysql_num_rows($result)==0)
{
$totalduration = "";
$seconds = 0;
$minutes = 0;
$computeSecMin = $seconds * $minutes;
$subSecMin = $computeSecMin + $duration;
$getMin = floor($subSecMin/60);
$getSec = $subSecMin%60;
$totalduration = $getMin .":". $getSec;
}
else{
$row = mysql_fetch_array($result);
$time = explode(":",$row['fldTotalDuration']);
$dur = explode(" ",$duration);
$computeSecMin = 60 * $time[0];
$subSecMin = $computeSecMin + $time[1] + $dur[0];
$getMin = floor($subSecMin/60);
$getSec = $subSecMin%60;
$totalduration = $getMin .":". $getSec;
}
}
$query = "INSERT INTO tbldata(fldNetname,fldBldgName,fldPlaylist,fldMonth,fldWeek,fldDuration,fldFrom,fldTo,fldTotalDuration) VALUES ('".$network."','".$bldg[$i]."','".$AdName."','".$month."','".$week."','".$duration."','".$from."','".$to."', '".$totalduration."')";
mysql_query($query) or die (mysql_error());
$duration = is came from another form where its a combobox/dropdown that is consists of 5s, 10s, 25s, 30s, 60s.
Currently, for adding the seconds is okay but for minutes is not good.
my problem for the computation is this "$getMin = floor($subSecMin/60); " .The result of this is "0" but it should be "1" because this computation is for "minutes".
Thanks for helping me with this problem.
Actually, what you got is what you should get.
If
$time = [0, 5]
and
$dur = [10, s]
then
$computeSecMin = 60 * $time[0] = 60*0 = 0
and
$subSecMin = $computeSecMin + $time[1] + $dur[0] = 0 + 5 + 10 = 15
Thus
$getMin = floor($subSecMin/60) = floor(15/60) = floor(0.25) = 0
It seems to me that you are computing it right, and the result is indeed 0 minutes.
The problem is your duration variable. It seems to me that your program is getting the wrong value. If I understand, it should be [1, 5] and not [0,5]. Check the function that is getting this value.
Here is what you are trying to do (sorry, I changed variables names, yours were not obvious):
$time = array(1,5);
$time_plus = '10s';
$time_plus = preg_replace('#\D#', '', $time_plus);
$minutes = $time [0] + (($time_plus + $time[1] >= 60) ? 1 : 0);
$seconds = ($time[1] + $time_plus) % 60;
echo $new_time = $minutes . ":" . $seconds;
Demo: http://codepad.org/eOBNeHrq
You may find using mysql for time manipulations will be cleaner for your application. AddTime() lets you do what you want with only seconds and minutes.
SELECT ADDTIME('00:32.50','1:27.50');
gives the result of:
01:59:01.000000
So, this adds 32.5 seconds to 1 minute 27.50 seconds = 1 minutes 59 seconds and .01 milliseconds.
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