Related
How to calculate minute difference between two date-times in PHP?
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 total5 years0 months10 days6 hours14 minutes2 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
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";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value
How to calculate minute difference between two date-times in PHP?
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 total5 years0 months10 days6 hours14 minutes2 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
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";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value
How to calculate minute difference between two date-times in PHP?
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 total5 years0 months10 days6 hours14 minutes2 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
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";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value
How to calculate minute difference between two date-times in PHP?
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 total5 years0 months10 days6 hours14 minutes2 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
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";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value
Let's say that I have two dates:
$initialDate = '08/10/2015 09:30:24 am';
$finalDate = '15/10/2015 15:47:38 pm';
$holiday = '12/10/2015';
I have to consider the hour of these days.
Hours to consider : 8 hours per day;
Start : 8 pm
End: 18 pm (24 hours format )
Lunch break start: 12:00 pm
Lunch break end: 14:00 pm
Example 1 : From 08/10/2015 10:00:00 to 09/10/2015 17:00:00 results 13 working hours. ( excludes lunch break )
Example 2 : From 08/10/2015 14:00:00 to 09/10/2015 18:00:00 results 12 working hours. ( Do not exclude 2 hours from begin date, because starts after 14:00 pm, lunch break )
Example 3 : From 08/10/2015 16:00:00 to 09/10/2015 18:00:00 results 10 working hours. ( Do not exclude 2 hours from begin date, because starts after 14:00 pmm lunch break )
Exampld 4 : From 08/10/2015 08:00:00 to 09/10/2015 11:00:00 results 14 working hours. ( Exclude 2 hours from begin date, and do not exclude 2 hours from end date, because isn't after 14:00 pm )
And I have to calculate the working hours and working days between those two dates, excluding weekends and Holidays, how can I do that ? I'm using PHP.
PS: I Already have something, but without lunch break... I made a research here on StackOverFlow.
Code:
function get_workdays($dataInicial,$dataFinal){
// arrays
$days_array = array();
$skipdays = array("Saturday", "Sunday");
$skipdates = get_feriados();
// other variables
$i = 0;
$current = $dataInicial;
if($current == $dataFinal) // same dates
{
$timestamp = strtotime($dataInicial);
if (!in_array(date("l", $timestamp), $skipdays)&&!in_array(date("Y-m-d", $timestamp), $skipdates)) {
$days_array[] = date("Y-m-d",$timestamp);
}
}
elseif($current < $dataFinal) // different dates
{
while ($current < $dataFinal) {
$timestamp = strtotime($dataInicial." +".$i." day");
if (!in_array(date("l", $timestamp), $skipdays)&&!in_array(date("Y-m-d", $timestamp), $skipdates)) {
$days_array[] = date("Y-m-d",$timestamp);
}
$current = date("Y-m-d",$timestamp);
$i++;
}
}
return $days_array;
}
function get_feriados(){
$dateAno = Date('Y');
$days_array = array(
$dateAno.'-10-12', // Padroeira do Brasil/ Dias das Crianças
$dateAno.'-11-02', // Finados
$dateAno.'-12-25' // Finados
);
return $days_array;
}
date_default_timezone_set('America/Sao_Paulo');
$dateAno = Date('Y');
$dataInicial = Date('08/10/2015 H:i');
$dataFinal = Date('13/10/2015 H:i');
// timestamps
$from_timestamp = strtotime(str_replace('/', '-', $dataInicial));
$to_timestamp = strtotime(str_replace('/', '-', $dataFinal));
// work day seconds
$workday_start_hour = 9;
$workday_end_hour = 17;
$workday_seconds = ($workday_end_hour - $workday_start_hour)*3600;
// work days beetwen dates, minus 1 day
$from_date = date('Y-m-d',$from_timestamp);
$to_date = date('Y-m-d',$to_timestamp);
$workdays_number = count(get_workdays($from_date,$to_date))-1;
$workdays_number = $workdays_number<0 ? 0 : $workdays_number;
// start and end time
$start_time_in_seconds = date("H",$from_timestamp)*3600+date("i",$from_timestamp)*60;
$end_time_in_seconds = date("H",$to_timestamp)*3600+date("i",$to_timestamp)*60;
// final calculations
$working_hours = ($workdays_number * $workday_seconds + $end_time_in_seconds - $start_time_in_seconds) / 86400 * 24;
print_r('<br/> Horas úteis '.$working_hours);
}
But don't consider two hours of break lunch. Can somebody please help me ?
If you use PHP 5.3 or higher, you can do this:
$datefrom = DateTime::createFromFormat('d/m/Y', '08/10/2015');
$dateto = DateTime::createFromFormat('d/m/Y', '15/10/2015');
$interval = $datefrom->diff($dateto);
$days = intval($interval->format('%a'));
Also you can remove holidays with if:
if ($datetime1->getTimestamp() < $holiday->getTimestamp() and $datetime2->getTimestamp() > $holiday->getTimestamp()) $days--;
Calculate hours between two days:
$datefrom = DateTime::createFromFormat('d/m/Y H:i:s', '08/10/2015 12:51:34');
$dateto = DateTime::createFromFormat('d/m/Y H:i:s', '15/10/2015 13:14:56');
$hours = intval($interval->format('%a')) * 24 + $interval->format('%h');
You can calculate hours of launches sum and then subtract it.
How to ignore weekends or calculate ignore days:
while($dateto->getTimestamp() > $datefrom->getTimestamp()) {
if (in_array($datefrom->format('w'), array('0','6'))) $ignore_days += 1;
$datefrom->modify('+1 day');
}
I expect this will do all you want. But I changed the datetime format as follows. Check it. Used less comments. If any query, please ask. Holidays are arrays, add and remove as required.
Times between 12:00 - 14:00 is handled.
Times below 08:00 is handled.
Times above 18:00 is handled.
<?php
$initialDate = '2015-10-13 08:15:00'; //start date and time in YMD format
$finalDate = '2015-10-14 11:00:00'; //end date and time in YMD format
$holiday = array('2015-10-12'); //holidays as array
$noofholiday = sizeof($holiday); //no of total holidays
//create all required date time objects
$firstdate = DateTime::createFromFormat('Y-m-d H:i:s',$initialDate);
$lastdate = DateTime::createFromFormat('Y-m-d H:i:s',$finalDate);
if($lastdate > $firstdate)
{
$first = $firstdate->format('Y-m-d');
$first = DateTime::createFromFormat('Y-m-d H:i:s',$first." 00:00:00" );
$last = $lastdate->format('Y-m-d');
$last = DateTime::createFromFormat('Y-m-d H:i:s',$last." 23:59:59" );
$workhours = 0; //working hours
for ($i = $first;$i<=$last;$i->modify('+1 day') )
{
$holiday = false;
for($k=0;$k<$noofholiday;$k++) //excluding holidays
{
if($i == $holiday[$k])
{
$holiday = true;
break;
} }
$day = $i->format('l');
if($day === 'Saturday' || $day === 'Sunday') //excluding saturday, sunday
$holiday = true;
if(!$holiday)
{
$ii = $i ->format('Y-m-d');
$f = $firstdate->format('Y-m-d');
$l = $lastdate->format('Y-m-d');
if($l ==$f )
$workhours +=sameday($firstdate,$lastdate);
else if( $ii===$f)
$workhours +=firstday($firstdate);
else if ($l ===$ii)
$workhours +=lastday($lastdate);
else
$workhours +=8;
}
}
echo $workhours; //echo the hours
}
else
echo "lastdate less than first date";
function sameday($firstdate,$lastdate)
{
$fmin = $firstdate->format('i');
$fhour = $firstdate->format('H');
$lmin = $lastdate->format('i');
$lhour = $lastdate->format('H');
if($fhour >=12 && $fhour <14)
$fhour = 14;
if($fhour <8)
$fhour =8;
if($fhour >=18)
$fhour =18;
if($lhour<8)
$lhour=8;
if($lhour>=12 && $lhour<14)
$lhour = 14;
if($lhour>=18)
$lhour = 18;
if($lmin == 0)
$min = ((60-$fmin)/60)-1;
else
$min = ($lmin-$fmin)/60;
return $lhour-$fhour + $min;
}
function firstday($firstdate) //calculation of hours of first day
{
$stmin = $firstdate->format('i');
$sthour = $firstdate->format('H');
if($sthour<8) //time before morning 8
$lochour = 8;
else if($sthour>18)
$lochour = 0;
else if($sthour >=12 && $sthour<14)
$lochour = 4;
else
{
$lochour = 18-$sthour;
if($sthour<=14)
$lochour-=2;
if($stmin == 0)
$locmin =0;
else
$locmin = 1-( (60-$stmin)/60); //in hours
$lochour -= $locmin;
}
return $lochour;
}
function lastday($lastdate) //calculation of hours of last day
{
$stmin = $lastdate->format('i');
$sthour = $lastdate->format('H');
if($sthour>=18) //time after 18
$lochour = 8;
else if($sthour<8) //time before morning 8
$lochour = 0;
else if($sthour >=12 && $sthour<14)
$lochour = 4;
else
{
$lochour = $sthour - 8;
$locmin = $stmin/60; //in hours
if($sthour>14)
$lochour-=2;
$lochour += $locmin;
}
return $lochour;
}
?>
Check the bellow code, that will return the number of Working days
function number_of_working_days($from, $to) {
$workingDays = [1, 2, 3, 4, 5];// date format = (1 = Monday,2 = Tue, ...)
$holidayDays = ['*-12-25', '*-02-14', '2015-12-23']; // variable and fixed holidays
$from = new DateTime($from);
$to = new DateTime($to);
$to->modify('+1 day');
$interval = new DateInterval('P1D');
$days = new DatePeriod($from, $interval, $to);
$no_of_working_days = 0;
foreach ($days as $day) {
if (!in_array($day->format('N'), $workingDays)||in_array($day->format('Y-m-d'), $holidayDays)||in_array($day->format('*-m-d'), $holidayDays)) {continue;}
$working_days++;
}
return $no_of_working_days;
}
echo number_of_working_days('2015-12-01', '2015-09-10');
From that you can easily calculate the Number of Working Hours.
I have created for you this nice class you can use. It requires the nesbot/carbon library (http://carbon.nesbot.com/) and you use it like so:
$calc = new HoursCalculator(
Carbon::createFromFormat("Y-m-d H:i", "2015-10-7 09:00"),
Carbon::createFromFormat("Y-m-d H:i", "2015-10-14 18:00"),
[
"2015-10-13"
]
);
echo $calc->getHours();
Heres the class:
class HoursCalculator {
const LUNCH_HOURS = 2;
protected $start;
protected $end;
protected $holidays;
protected $hoursTotal;
public function __construct(Carbon $start, Carbon $end, $holidays = [])
{
$this->start = $start;
$this->end = $end;
$this->holidays = $holidays;
}
public function getHours()
{
$dayHours = $this->getHoursInADay();
return $this->calculateHours($dayHours);
}
protected function getHoursInADay()
{
$start = $this->start;
$end = Carbon::createFromFormat("Y-m-d H:i", $this->start->format("Y-m-d") . " " . $this->end->format("H:i"));
return $start->diffInHours($end) - self::LUNCH_HOURS;
}
protected function getStartDate()
{
return $this->start->format('Y-m-d');
}
protected function calculateHours($hoursInDay)
{
$start = $this->start->copy()->startOfDay();
$end = $this->end->copy()->endOfDay();
$days = 0;
while($start->lt($end)) {
if (!$this->isHoliday($start) && !$this->isWeekend($start)) {
$days++;
}
$start->addDay(1);
}
return $days * $hoursInDay;
}
protected function isHoliday(Carbon $date)
{
$date->startOfDay();
foreach($this->holidays as $holiday) {
$holiday = Carbon::createFromFormat("Y-m-d", $holiday)->startOfDay();
if ($date->eq($holiday)) {
return true;
}
}
return false;
}
protected function isWeekend(Carbon $date)
{
return $date->isWeekend();
}
}
Hope this helps!