337

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

Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236

21 Answers21

487

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

mike
  • 5,015
  • 2
  • 15
  • 4
  • 17
    Pitty DateInterval does not have method like `inSeconds()` or something similar, now it's code repetition everywhere I need to calculate difference in seconds. – Marius Balčytis Nov 29 '12 at 07:32
  • 5
    @barius Or you can write a function that wraps the repeating code, or even extend DateTime and not repeat your code. – Anther Apr 16 '13 at 17:41
  • 19
    +1 for the only proper answer at the time of writing this comment. – N.B. Jul 11 '13 at 12:49
  • 10
    Using the new DateTime class is good, but why generate a DateInterval that then has to be decoded so awkwardly? `$dateFrom = new DateTime('2007-09-01 04:10:58'); $dateTo = new DateTime('2012-09-11 10:25:00'); echo ($dateTo->getTimestamp()-$dateFrom->getTimestamp())/60 ;` – dkloke Dec 14 '14 at 22:43
  • @dkloke: because that would use a classic unix timestamp which means we have to deal with dates before 1970 and leap years and so on on our own. – Hafenkranich May 16 '15 at 22:42
  • 1
    @Raphael Weber that's true for some earlier versions, I tried this in 5.3.15 and subsequent version and getTimestamp() gives negative numbers for DateTimes prior to the unix epoch, and hence correct calculations; I checked some trivial pre-epoch leap year examples and the calculations were correct. But it is version sensitive, a user note under DateTime:getTimestamp suggests that using `format("U")` is more reliable for a version that returns false for getTimestamp(). – dkloke May 17 '15 at 07:49
  • 2
    Can someone explain to me why this is better than the `strtotime` answer above it? This seems like a case of OOP when Procedural is AT LEAST as valid (and considerably more concise) solution. – Bing Jul 25 '16 at 05:05
  • 1
    How to know if difference is in plus or minus? – m.qayyum Jul 29 '16 at 20:41
  • 1
    The "old way" **does** take in to account daylight savings and timezones so I can't really see any useful benefits of using DateTime **in this situation**. @Hafenkranich That would be awful if leap years could distort a unix timestamp. Thankfully they thought of that. – Phil Oct 04 '16 at 21:56
  • 1
    @Phil_1984_ true. Probably didn't have enough coffee that day. Still I'd rather stick with DateTime and never mix usage of these two. It just simplifies things. So even when it ist not necessary for this particular usecase, i would generally stick with DateTime. – Hafenkranich Oct 05 '16 at 14:24
  • Not every day has 24 hours so this solution won't actually take into account daylight savings. I don't have a better suggestion though :/ Pity DateInterval doesn't have methods for this sort of thing. – ARW May 06 '18 at 18:22
  • You might aswell edit your 'above' answer because you are taking the the draw with my vote and soon hopefully the lead :) – ii iml0sto1 May 14 '18 at 13:13
  • I understood **`$minutes = $since_start->days * 24 * 60;`** , because there are 24 hours in a day and 60 minutes in an hour, `totalNumberOfDays * 24 * 60` does give us the total number of minutes. But then why do we **_again_** do `$minutes += $since_start->h * 60;` and `$minutes += $since_start->i;` in the next two lines? – Shy Nov 05 '18 at 05:44
  • Good answer I suggest to add sign :`(int)($interval->format('%R').$minutes);` – nourhero Sep 16 '20 at 02:27
  • @dkloke your answer was simple and discards all the concerns about seconds calculation... – vkGunasekaran Jul 01 '21 at 02:52
  • This answer does not let me know whether the time difference is in the future or past. Swap the two date inputs, same results appear in $since_start. – a coder Sep 22 '21 at 12:28
  • For me, DateTime API is a little confusing. I expected `$since_start->i` to be equal to `2645654 minutes` without extra calculations – userlond Oct 16 '21 at 10:21
  • Also do not forget $since_start->invert which is 1 or 0 depending on if the difference is negative or positive. If you want to tell if the amount is less than or greater than 0. – Dave Hubbard Mar 30 '23 at 15:51
378

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";
Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
user38526
  • 3,843
  • 2
  • 15
  • 2
  • 5
    abs() function not required if anyone wish to check negative time too! – Pran Dec 12 '15 at 06:09
  • 42
    For those wondering, the `/ 60,2` means: divide by sixty, round to the nearest two decimal places. – Bing Jul 25 '16 at 05:09
  • 3
    strtotime is unreliable, avoid. Only works for specific date formats, mostly US-related. – sivann Sep 26 '16 at 15:06
  • 15
    `strtotime` may be obsolete but it's not unreliable if you use it properly. It stands to reason you need to be working with consistent date formats to be able to read (or parse) the dates correctly. See `ISO 8601` and don't blame the tools :=) – Phil Oct 04 '16 at 21:29
107

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

Noman
  • 1,459
  • 2
  • 18
  • 38
Oli
  • 235,628
  • 64
  • 220
  • 299
  • 3
    @Jerald How this solution works for you? Do you mind to brief it at least a little bit? Thanks. – Wafie Ali Mar 29 '17 at 01:59
  • 11
    @WafieAli $nInterval = strtotime($sDate2) - strtotime($sDate1); this will return the time difference in seconds, then you can just divide by 60 like this. $nInterval = $nInterval/60; – Jerald Jul 11 '17 at 10:27
  • 1
    +1 for explaining what needs to be done and not using the useless DateInterval class that doesn't have a method to do just that: return difference *in minutes*. – AndreKR Jun 10 '19 at 19:47
42
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
Tom
  • 8,536
  • 31
  • 133
  • 232
  • Can you explain why you need some `sleep` to calculate a date difference? – Nico Haase Feb 01 '19 at 08:55
  • 5
    What better way to use your time whilst waiting for another time to compare to than have a quick sleep. although this should in theory give you an answer of 2, which could help people trying to understand the formula, confirming it's correct. – slappy-x Feb 05 '19 at 23:59
  • @NicoHaase `sleep()` is basically used to delay the execution of the current script by a specified number of seconds. So here it is being used just to demonstrate a decent or a good enough amount of time difference. Thanks. – YDF Feb 03 '22 at 04:50
30
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>

Output:

75
Rahilkhan Pathan
  • 504
  • 6
  • 13
19

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;
Şafak Gezer
  • 3,928
  • 3
  • 47
  • 49
18

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.

yussan
  • 2,277
  • 1
  • 20
  • 24
  • 1
    Strange, for me, executing that code does not provide the time difference in minutes – Nico Haase Feb 01 '19 at 08:56
  • 2
    This is useful only if you want to output "1hr 14mins". If you want only minutes, for example), you'd have to do the math: ($diff->h * 60) + $diff->i) – GDP Jan 10 '20 at 16:26
  • `This is useful only if...` and then you provided a counterexample to how it is useful beyond the stated condition. So, it is useful, but it requires another step for the stated problem. That's different. – Anthony Mar 04 '23 at 12:47
16

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);
Muhammad
  • 3,169
  • 5
  • 41
  • 70
  • 4
    If you want days, too, than you add `$days = $interval->format('%d');` and the diff is `($days * 1440 + $hours * 60 + $minutes)` . For months, years => same logic – Seer Jan 22 '14 at 11:01
13

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.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Raj Nandan Sharma
  • 3,694
  • 3
  • 32
  • 42
  • This produces grammatically incorrect strings whenever the unit is 1. "1 Seconds", "1 Hours", etc. It should really be `return "{$unit} unit" . ($unit != 1 ? "s" : "");` – Anthony Mar 04 '23 at 12:41
12

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;
}
Yubraj Pokharel
  • 477
  • 8
  • 23
11

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;
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
hriziya
  • 1,116
  • 1
  • 23
  • 41
8
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";
        }
}
Veerendra
  • 2,562
  • 2
  • 22
  • 39
8

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
besimple
  • 444
  • 1
  • 7
  • 12
8

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;
MB_18
  • 1,620
  • 23
  • 37
2

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.

Ali Han
  • 509
  • 7
  • 10
2
$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.

1

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

Here is a simple one-liner:

$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
nimrod
  • 5,595
  • 29
  • 85
  • 149
0

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;     
}
GYaN
  • 2,327
  • 4
  • 19
  • 39
0

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

Sumit Kumar Gupta
  • 2,132
  • 1
  • 22
  • 21
-2

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 
Hamza Qureshi
  • 172
  • 2
  • 20