PHP hours and minutes between two times - php

$time1 = "14:45";
$time2 = "15:55";
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
echo "<b>$hours</b> hours and<b>$minutes</b> minutes</b>";
This code works good if the variable time1 is lower than variable time2, but if the time1 is "23:35" and time2 is "01:40" it will output "-22 hours and -55 minutes".
How can I correct this so it still will output the hours and minutes between the both times even if the time1 is lower than time2 variable
This code will take two times example "14:45" and "16:33" and calculate how many hours and minutes it is between each time, but it doesn't work if "time1" is lower than "time2" (time1 and time2 is variables)
http://codepad.org/QmFdN6RV

This is how I would do it, using strtotime():
// If dates are not specified, strtotime() will assume both are from today
$time1 = "23:45";
$time2 = "01:24";
// Absolute value of time difference in seconds
$diff = abs(strtotime($time1) - strtotime($time2));
// Convert $diff to minutes
$tmins = $diff/60;
// Get hours
$hours = floor($tmins/60);
// Get minutes
$mins = $tmins%60;
See demo
This assumes that $time1 and $time2 are from the same day. If not, then this will need to be specified.
$time1 = "today 23:45";
$time2 = "tomorrow 01:24";
// or
$time1 = "2014-7-3 23:45";
$time2 = "2014-7-4 01:24";
// or some other method of specifying the day.
See demo 2

So dont know what you really want as result - could be two ways, so i do both ;)
you have also to use floor and not round.
First solution is, that you get the difference based on same day:
<?php
$time1 = "23:45";
$time2 = "01:44";
list($hours, $minutes) = explode(':', $time1);
$firstTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$secondTimestamp = mktime($hours, $minutes);
$firstTimestamp > $secondTimestamp?$seconds = $firstTimestamp - $secondTimestamp:$seconds = $secondTimestamp - $firstTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = floor($seconds / (60 * 60));
echo "<b>$hours</b> hours and <b>$minutes</b> minutes</b>";
?>
output would be: 22 hours and 1 minutes
the second way is, that the endtime (named it secondtime) is the next day
than it should be like
<?php
$time1 = "23:45";
$time2 = "01:24";
list($hours, $minutes) = explode(':', $time1);
$firstTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$secondTimestamp = mktime($hours, $minutes);
$seconds = $secondTimestamp - $firstTimestamp;
$seconds<0?$seconds+=24*60*60:"";
$minutes = ($seconds / 60) % 60;
$hours = floor($seconds / (60 * 60));
echo "<b>$hours</b> hours and <b>$minutes</b> minutes</b>";
?>
output would be: 1 hours and 39 minutes
url to codepad: http://codepad.org/7plRAhZJ

if the seconds are negative, add 24 hours to them:
$time1 = "23:35";
$time2 = "1:40";
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);
$seconds = $endTimestamp - $startTimestamp;
if($seconds < 0) {
$seconds+=60*60*24;
}
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
echo "<b>$hours</b> hours and<b>$minutes</b> minutes</b>";

You would do this way:
$time1 = "23:40";
$time2 = "01:40";
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);
$seconds = abs($endTimestamp - $startTimestamp);
$diff = (24*60*60)-$seconds;
if ($diff < $seconds) {
$seconds = $diff;
}
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
echo "<b>$hours</b> hours and<b>$minutes</b> minutes</b>"
Note that this will never give you diferences bigger than 12h.
For instance, the difference between 06:00 and 22:00 will be 8 hours

You could use date_diff
$date1 = new DateTime();
$date2 = new DateTime();
$date1->setTimestamp($startTimestamp);
$date2->setTimestamp($endTimestamp);
$interval = date_diff($date1, $date2);
//or $interval = $date1->diff($date2)
echo $interval->format('%h hours and %m minutes');

Related

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

MySQL Time differencials

I am using php and mysql to create an automated html email report. This report shows the total number of emails received and logged into our system by a particular client. This is broken down by month in the given year. It also shows the average turn time from the point the email was said to be received, and the point that the ticket (ticket is logged into our database with information regarding email) is closed. Currently, I am using the following query and function to get the average turn time each month. I was told that they want to calculate the turn time based upon business hours, 8-8, not a full 24 hour day.
How can I calculate an average turn time between assuming that the time allotted in a day is 12 hours (8-8)?
If an email was received 21:00:00 Monday, and the ticket was closed 8:05:00 Tuesday, the turn time would equal 00:05:00 or 5 minutes.
$year = date("Y");
$month_num = date('m');
$total_time = "00:00:00";
for($m = 1; $m<=12; $m++)
{
$month = date('F', mktime(0,0,0,$m, 1, date('Y')));
$turn_time = GetTurnTime($month, $year);
$message .= '<td align="center">'.$turn_time['Time'].'</td>';
$total_time = sum_the_time($total_time, $turn_time['Time']);
$average_time = sum_the_average($total_time, $turn_time['Time'], $month_num);
}
function GetTurnTime($month, $year)
{
$turn_time = mysql_fetch_assoc(mysql_query("SELECT sec_to_time(AVG(SEC_TO_TIME(time_to_sec(TIMEDIFF(closed_on, received_on))))) AS `Time`, DATE_FORMAT(received_on, '%m/%d/%Y') as `Date` from `calltrak`.`calls` where monthname(received_on) = '{$month}' and year(received_on) = '{$year}' and ticket_status = 'CLOSED' and ticket_source = '2' and dept_id in (select dept_id from depts where bus_id = '4') and cust_name = 'SOMECOMPANY'"));
return $turn_time;
}
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;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
function sum_the_average($time1, $time2, $month)
{
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$seconds = $seconds / $month;
round($seconds);
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

calculate time duration considering the dates in PHP

How can I calculate time duration considering the datestamp in PHP? the date format I used in between dates is "Y-m-d H:i:s",
My working code can only compute the duration between time without considering the date.
below is my code:
$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";
function hmsDiff ($assigned_time, $completed_time) {
$assigned_seconds = hmsToSeconds($assigned_time);
$completed_seconds = hmsToSeconds($completed_time);
$remaining_seconds = $assigned_seconds - $completed_seconds;
return secondsToHMS($remaining_seconds);
}
function hmsToSeconds ($hms) {
$total_seconds = 0;
list($hours, $minutes, $seconds) = explode(":", $hms);
$total_seconds += $hours * 60 * 60;
$total_seconds += $minutes * 60;
$total_seconds += $seconds;
return $total_seconds;
}
function secondsToHMS ($seconds) {
$minutes = (int)($seconds / 60);
$seconds = $seconds % 60;
$hours = (int)($minutes / 60);
$minutes = $minutes % 60;
return sprintf("%02d", abs($hours)) . ":" .
sprintf("%02d", abs($minutes)) . ":" .
sprintf("%02d", abs($seconds));
}
The DateTime has a "diff" method which returns an Interval object. The interval object has a method "format" which allows you to customize the output.
#!/usr/bin/env php
<?php
$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";
$d1 = new DateTime($assigned_time);
$d2 = new DateTime($completed_time);
$interval = $d2->diff($d1);
echo $interval->format('%d days, %H hours, %I minutes, %S seconds');
NOTE: If you are not using 5.3.0+, there is a good answer here: https://stackoverflow.com/a/676828/128346.
Not completely knowing what you want, what about something like:
// prevents php error
date_default_timezone_set ( 'US/Eastern' );
// convert to time in seconds
$assigned_seconds = strtotime ( $assigned_time );
$completed_seconds = strtotime ( $completed_time );
$duration = $completed_seconds - $assigned_seconds;
// j gives days
$time = date ( 'j g:i:s', $duration );

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

Time diff in minutes between 2 dates

Got this working on php 5.3
$datetime1 = new DateTime("2011-10-10 10:00:00");
$datetime2 = new DateTime("2011-10-10 10:45:00");
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
How can i make it work on php 5.2 ? are there any equivalent functions available??
Got it working
$date1 = "2011-10-10 10:00:00";
$date2 = "2011-10-10 10:11:00";
echo round((strtotime($date2) - strtotime($date1)) /60);
Instead of DateTime you can use strtotime and date:
$datetime1 = strtotime("2011-10-10 10:00:00");
$datetime2 = strtotime("2011-10-10 10:45:00");
$interval = abs($datetime2 - $datetime1);
$minutes = round($interval / 60);
echo 'Diff. in minutes is: '.$minutes;
If you need the minutes spanning several days you could add this one into the mix:
$days = $interval->format("%d");
if ($days > 0) {
return ($hours * 60 + $minutes) + ($days * 24 * 60);
}
Try this
function time_Diff_Minutes($startTime, $endTime) {
$to_time = strtotime($endTime);
$from_time = strtotime($startTime);
$minutes = ($to_time - $from_time) / 60;
return ($minutes < 0 ? 0 : abs($minutes));
}
echo time_Diff_Minutes("2008-12-13 20:00:00","2008-12-14 08:00:00"); //output 720
echo time_Diff_Minutes("2008-12-14 20:00:00","2008-12-13 08:00:00"); //output 0 (startTime > endTime) Ternary will return 0

Categories