Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time difference in minutes in PHP

How to calculate minute difference between two date-times in PHP?

like image 448
Tom Smykowski Avatar asked Dec 13 '08 13:12

Tom Smykowski


People also ask

How do you calculate time difference between minutes?

To get the time difference in a single time unit (hours ,minutes or seconds), you can perform the following calculations. Total minutes between two times: To calculate the minutes between two times, multiply the time difference by 1440, which is the number of minutes in one day (24 hours * 60 minutes = 1440).

How can I get the difference between two time in PHP?

php $start = strtotime("12:00"); $end = // Run query to get datetime value from db $elapsed = $end - $start; echo date("H:i", $elapsed); ?>


2 Answers

The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm. Eg.

$start_date = new DateTime('2007-09-01 04:10:58'); $since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00')); echo $since_start->days.' days total<br>'; echo $since_start->y.' years<br>'; echo $since_start->m.' months<br>'; echo $since_start->d.' days<br>'; echo $since_start->h.' hours<br>'; echo $since_start->i.' minutes<br>'; echo $since_start->s.' seconds<br>'; 

$since_start is a DateInterval object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).

The above code will output:

1837 days total
5 years
0 months
10 days
6 hours
14 minutes
2 seconds

To get the total number of minutes:

$minutes = $since_start->days * 24 * 60; $minutes += $since_start->h * 60; $minutes += $since_start->i; echo $minutes.' minutes'; 

This will output:

2645654 minutes

Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time http://www.php.net/manual/en/book.datetime.php

like image 127
mike Avatar answered Sep 22 '22 12:09

mike


Here is the answer:

$to_time = strtotime("2008-12-13 10:42:00"); $from_time = strtotime("2008-12-13 10:21:00"); echo round(abs($to_time - $from_time) / 60,2). " minute"; 
like image 38
user38526 Avatar answered Sep 23 '22 12:09

user38526