0

how to get the time difference between 2 values while if second value is past the current time?

i use below code:

function time_diff($date2, $date1, $format){

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));  

$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));  

$days = floor(($diff - $years * 365*60*60*24 -  $months*30*60*60*24)/ (60*60*24)); 

$hours = floor(($diff - $years * 365*60*60*24  - $months*30*60*60*24 - $days*60*60*24) / (60*60));  

$minutes = floor(($diff - $years * 365*60*60*24  - $months*30*60*60*24 - $days*60*60*24  - $hours*60*60)/ 60);  

$seconds = floor(($diff - $years * 365*60*60*24  - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minutes*60)); 


if ($format == 'year'){
 $i = $years;
}elseif ($format == 'month'){
 $i = $months;
}elseif ($format == 'day'){
 $i = $days;
}elseif ($format == 'hour'){
 $i = $hours;
}elseif ($format == 'minutes'){
 $i = $minutes;
}elseif ($format == 'second'){
 $i = $seconds;
}

return $i;

}

i want to get time difference between (saved time in database) and (current time).

everything is fine, but when (saved time in database) passes and its smaller than (current time), this code return value but without negative sign.

i mean if time difference is 2 day, it return 2 while it should return (-2) or somethings like that cuz (saved time in database) passes and its smaller than (current time).

  • Why don't you use composer to parse the dates ? – Dhaval Chheda Jun 03 '20 at 14:04
  • You are making many false assumptions here. [Not every day has 24 hours. Not every year has 365 days. Most months don't have 30 days.](https://gist.github.com/thanatos/eee17100476a336a711e) Time computations always depend on a location (possibly an abstract one, such as UTC). Use [DateTime::diff](https://www.php.net/manual/en/datetime.diff.php). – Peter Jun 03 '20 at 14:07
  • Try to read This post https://stackoverflow.com/questions/13928021/getting-time-difference-between-two-times-in-php – user1781038 Jun 03 '20 at 14:09
  • https://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates might also be relevant – Mehmet Karatay Jun 03 '20 at 15:21

1 Answers1

0

you used $diff = abs(strtotime($date2) - strtotime($date1));, while abs() stands for absolute (as in the result is always positive) using strtotime($date2) - strtotime($date1) should work instead

MeowBlock
  • 11
  • 4