Date and Time Difference calculates in PHP


/ Published in: PHP
Save to your folder(s)

Calculate date time difference


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.