PHP - Difference between Time in Minutes - php

I'm trying to calculate the difference of two times. I'm using this method to return the difference in minutes.
$datetime1 = new DateTime('9.00am');
$datetime2 = new DateTime('10.15am');
$interval = $datetime1->diff($datetime2);
$timeDuration = $interval->format('%im');
However, the $timeDuration returns 15m instead of 75m.
Any help that could correct the code to let it return the exact correct difference in minutes ?

Because the difference between 9am and 10:15am is 1 hour ($interval->h) and 15 minutes ($interval->i), not 75 minutes literally.
If you wish to get the total number of minutes, you have to calculate it:
$differenceInMinutes = $interval->i + ($interval->h * 60);
If you wish to have more universal solution, I would go for the unix time:
$differenceInSeconds = abs($datetime1->format('U') - $datetime2->format('U'));
$differenceInMinutes = ceil($differenceInSeconds / 60);

The simple way to get different in minutes
<?php
$start = date_create('1990-01-01 09:00:00');
$end = date_create('1990-01-01 10:15:00');
$interval=date_diff($end, $start);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$in_minutes = $hours * 60 + $minutes;
echo 'Diff. in minutes is: '.$in_minutes;
?>

When you are trying to calculate the difference between two DateTime's like $datetime1 = new DateTime('9.00am'); and $datetime2 = new DateTime('10.15am'); you know that the difference is 75 minutes, but the resulto of diff() method is 1 hour for $interval->h and 15 minutes for $interval->i. So this is how you can calculate it:
$datetime1 = new DateTime('9.00am');
$datetime2 = new DateTime('10.15am');
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
$difference_in_minutes = $hours * 60 + $minutes;
echo 'Difference in minutes is: ' . $difference_in_minutes . "\n";
There a working snipped in this link

Related

Add fractional hours to a DateTime in php

I have a system which I need to add a certain amount of fractional hours.
I've been searching and this is what I got, by far it's the most accurate method, but still doesn't give me the answer I need
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = array();
$time = explode(".", $hours);
$time [1] += $time [0]*60;
$now->modify("+".$time[1]." hours");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer ->format('Y-m-d H:i:s');
The answer that I want to reach is "2017-11-09 11:00:00" and I receive "2017-10-25 12:22:23" instead
Adding the hours is not correct. When you multiply hours times 60 it will make minutes.
This code should work.
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
$time = explode(".", $hours);
$time[1] += $time[0]*60;
$now->modify("+".$time[1]." minutes");
return $now;
}
$diff = 119.23;
$answer = calculateHours($diff);
echo $answer->format('Y-m-d H:i:s');
Result is 2017-10-30 09:46:00
You should use DateInterval php class to create an inverval with x seconds from your $hours variable.
Then you just have to use the datetime add interval method to modify your date
Please take a look a this example
function calculateHours($hours){
$now = new DateTime("2017-10-25 10:23:00");
var_dump($now);
$timeParts = explode(".", $hours);
// Where 23 is a percentage of on hour
$minutes = $timeParts[0] * 60 + round($time[1] * 60 / 100);
// Where 23 is the number of minutes
$minutes = $timeParts[0] * 60 + $time[1];
$interval = new DateInterval(sprintf('PT%dM', $minutes));
$now->add($interval);
echo $now->format('Y-m-d H:i:s');
return $now;
}
Use date_add
date_add($now, date_interval_create_from_date_string($tempo[1]' hours'));
or as object:
$now->add( DateInterval::createFromDateString($tempo[1].' hours'));

Difference between 2 datetimes in minutes?

I got the following code:
$now = new DateTime();
$then = new DateTime($accountExists['sub_limit']);
$interval = $then->diff($now);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
which returns the difference between 2 datetimes in minutes. If then is 2015-05-31 19:15:31 and now is 2015-05-31 19:20:31 it returns 5 minutes. But as soon as the day changes, if then changes to 2015-05-30 19:15:31 it still returns 5 minutes when it should be 1445 minutes. Could someone point out my error?
Because months, years can have an arbitrary number of minutes, you might best want to convert your dates to timestamps (seconds since epoch) so you only have to divide by 60. Fortunately, it's easy to do so:
$now = new DateTime('2015-05-31 19:20:31');
$then = new DateTime('2015-05-30 19:15:31');
$seconds = abs($now->format('U') - $then->format('U'));
$minutes = floor($seconds / 60);
print $minutes;
That is because it's a full day. So you have to calculate how many minutes one day is. So this should work for you:
Basically here I just get all days, hours, minutes and seconds from the interval and multiply them by the multiplier to get minutes out of them.
<?php
//Test data
$now = "2015-05-30 19:20:31";
$accountExists['sub_limit'] = "2015-05-30 19:15:31";
$now = new DateTime($now);
$then = new DateTime($accountExists['sub_limit']);
$interval = $then->diff($now);
$multiplier = ["days" => 60*24, "h" => 60, "i" => 1, "s" => 1/60];
$minutes = 0;
$values = array_intersect_key((array)$interval, $multiplier);
foreach($values as $k => $v)
$minutes += $v*$multiplier[$k];
echo "Diff. in minutes is: " . $minutes;
?>
output:
Diff. in minutes is: 1445

Want to subtract hour to hour, minutes to minutes, and seconds to seconds from between two dates

<?php
$ts='2011-04-13 23:00:00';
$ts1='2011-04-14 15:45:00';
echo $addtime = date("h:i:s", mktime(date("h", $ts1)- date("h", $ts),date("i", $ts1)- date("i", $ts),date("s", $ts1)- date("s", $ts),0,0,0));
?>
It gives a result but it is not correct in many cases. How do I fix it?
Your expected result would be 16:45:00 for the given example, right? So you want the difference between the two given dates in hours:minutes:seconds.
<?php
//initial strings
$ts='2011-04-13 23:00:00';
$ts1='2011-04-14 15:45:00';
//converting to time
$start = strtotime($ts);
$end = strtotime($ts1);
//calculating the difference
$difference = $end - $start;
//calculating hours, minutes and seconds (as floating point values)
$hours = $difference / 3600; //one hour has 3600 seconds
$minutes = ($hours - floor($hours)) * 60;
$seconds = ($minutes - floor($minutes)) * 60;
//formatting hours, minutes and seconds
$final_hours = floor($hours);
$final_minutes = floor($minutes);
$final_seconds = floor($seconds);
//output
echo $final_hours . ":" . $final_minutes . ":" . $final_seconds;
?>
This gives me correct results. Hope I got your problem right!

How to get the hour minute and second?

The future time is :2012-05-26 00:00:00
supposed there are three variable: $hour $minute $second
now, i want to using the future time subtract now time. then give the left hour to $hour,give the left minute to $minute,give the left second to $second.
i am sorry i am new of php, now i get stucked how to do the math operation ? thank you
A very good resource for dates and time..
http://www.php.net/manual/en/function.time.php
-there are samples here doing something similar.
Check the date_diff function. There's the exact solution to what you're asking there.
And here's the page (DateInterval::format) documenting how you can format the output.
$now = date_create();
// use "now" and necessary DateTimeZone in the arguments
$otherDate = date_create('2020-04-13');
$interval = date_diff($now, $futureDate);
echo $interval->format('%a days');
The following are the math operations for the difference in hours,minutes and seconds
$future_datetime = '2012-05-26 00:00:00';
$future = strtotime($future_datetime); //future datetime in seconds
$now_datetime = date('Y-m-d H:i:s');
$now = date('U'); //now datetime in seconds
//The math for calculating the difference in hours, minutes and seconds
$difference = $future - $now;
$second = 1;
$minute = 60 * $second;
$hour = 60 * $minute;
$difference_hours = floor($difference/$hour);
$remainder = $difference - ($difference_hours * $hour);
$difference_minutes = floor($remainder/$minute);
$remainder = $remainder - ($difference_minutes * $minute);
$difference_seconds = $remainder;
echo "The difference between $future_datetime and $now_datetime is $difference_hours hours, $difference_minutes minutes and $difference_seconds seconds";

How do I find the hour difference between two dates in PHP?

I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.
You can use DateTime class also -
$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference
As an addition to accepted answer I would like to remind that \DateTime::diff is available!
$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);
/**
* #var \DateInterval $diff
*/
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise
\DateInterval documentation.
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
You can try this :
$time1 = new DateTime('06:56:58');
$time2 = new DateTime('15:35:00');
$time_diff = $time1->diff($time2);
echo $time_diff->h.' hours';
echo $time_diff->i.' minutes';
echo $time_diff->s.' seconds';
Output:
8 hours 38 minutes 2 seconds
The problem is that using these values the result is 167 and it should be 168:
$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
$date1 = date_create('2016-12-12 09:00:00');
$date2 = date_create('2016-12-12 11:00:00');
$diff = date_diff($date1,$date2);
$hour = $diff->h;
This is because of day time saving.
Daylight Saving Time (United States) 2014 began at 2:00 AM on
Sunday, March 9.
You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to
$date2 = "2014-03-14 05:49:23";
You can try this:
$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
You can use strtotime() to parse your strings and do the difference between the two of them.
Resources :
php.net - strtotime()

Categories