获取两个日期之间的天数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取两个日期之间的天数相关的知识,希望对你有一定的参考价值。

  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. ?>

以上是关于获取两个日期之间的天数的主要内容,如果未能解决你的问题,请参考以下文章

Java获取两个日期之间的天数[重复]

SQL SERVER:获取两个日期之间的总天数

如何获取 MySQL 上两个日期之间的差异天数?

C++ 计算两个日期之间的天数

PHP 获取两个日期之间的天数

如何获取 Oracle 11g 中两个日期之间的天数? [复制]