Posted By

fwso on 03/17/10


Tagged

time date DateTime difference


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

dantreacy
undyingheart


Date and Time Difference calculates in PHP


 / Published in: PHP
 

URL: http://stackoverflow.com/questions/388673/php-date-calculation

Calculate date time difference

  1. /**
  2.  * Calculates the differences between two date
  3.  *
  4.  * @param date $date1
  5.  * @param date $date2
  6.  * @return array
  7.  */
  8. function dateDifference($date1, $date2)
  9. {
  10. $d1 = (is_string($date1) ? strtotime($date1) : $date1);
  11. $d2 = (is_string($date2) ? strtotime($date2) : $date2);
  12.  
  13. $diff_secs = abs($d1 - $d2);
  14. $base_year = min(date("Y", $d1), date("Y", $d2));
  15.  
  16. $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
  17.  
  18. return array
  19. (
  20. "years" => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
  21. "months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
  22. "months" => date("n", $diff) - 1,
  23. "days_total" => floor($diff_secs / (3600 * 24)),
  24. "days" => date("j", $diff) - 1,
  25. "hours_total" => floor($diff_secs / 3600),
  26. "hours" => date("G", $diff),
  27. "minutes_total" => floor($diff_secs / 60),
  28. "minutes" => (int) date("i", $diff),
  29. "seconds_total" => $diff_secs,
  30. "seconds" => (int) date("s", $diff)
  31. );
  32. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: undyingheart on February 1, 2012

Warning: date_diff() expects parameter 1 to be DateTime, string given in /x/y/z/t.php on line 388

I think this is related with php version (got this warning in php 5.3.9)

Any suggestion?

You need to login to post a comment.