简体   繁体   中英

How to subtract two dates and get the difference in minutes PHP

So i have two dates that are in hour format. I want to subtract them together and get the difference in minutes.

 $time = '01:47'; $time2 = '01:50'; $finalresult = $time2 - $time; 

Another approach:

echo date_diff(new DateTime('01:47'), new DateTime('01:50'), true)->i;

The third parameter, true , is to force a positive result and the i is to get the minutes from the DateInterval returned by date_diff .

$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*60+$mins;

another method

$to_time = strtotime("01:47:00");
$from_time = strtotime(" 01:55:00");
echo round(abs($to_time - $from_time) / 60). " minute";

The easiest solution is probably to use strtotime and divide by 60:

$time = strtotime('01:47');
$time2 = strtotime('01:50');

$finalresult = ($time2 - $time) / 60;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM