Get number of days between two dates


 / Published in: PHP
 

  1. <?php
  2. /**
  3.  * Calculating the difference between two dates
  4.  * @author: Elliott White
  5.  * @author: Jonathan D Eisenhamer.
  6.  * @link: http://www.quepublishing.com/articles/article.asp?p=664657&rl=1
  7.  * @since: Dec 1, 2006.
  8.  */
  9.  
  10. if( function_exists( 'date_default_timezone_set' ) )
  11. {
  12. // Set the default timezone to US/Eastern
  13. date_default_timezone_set( 'US/Eastern' );
  14. }
  15.  
  16. // Will return the number of days between the two dates passed in
  17. function count_days( $a, $b )
  18. {
  19. // First we need to break these dates into their constituent parts:
  20. $gd_a = getdate( $a );
  21. $gd_b = getdate( $b );
  22.  
  23. // Now recreate these timestamps, based upon noon on each day
  24. // The specific time doesn't matter but it must be the same each day
  25. $a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
  26. $b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
  27.  
  28. // Subtract these two numbers and divide by the number of seconds in a
  29. // day. Round the result since crossing over a daylight savings time
  30. // barrier will cause this time to be off by an hour or two.
  31. return round( abs( $a_new - $b_new ) / 86400 );
  32. }
  33.  
  34. // Prepare a few dates
  35. $date1 = strtotime( '12/3/1973 8:13am' );
  36. $date2 = strtotime( '1/15/1974 10:15pm' );
  37. $date3 = strtotime( '2/14/2005 1:32pm' );
  38.  
  39. // Calculate the differences, they should be 43 & 11353
  40. echo "<p>There are ", count_days( $date1, $date2 ), " days.</p>\n";
  41. echo "<p>There are ", count_days( $date2, $date3 ), " days.</p>\n";
  42. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jokonardi on July 3, 2010

hey..thanks your article ... but ..if i must check how many saturday in date range ($date1,$date2)? i need your help please

Posted By: phish3rz on September 10, 2011

Could you provide an example of how to call this function please?

You need to login to post a comment.