PHP计算两个时间相差的年数、月数和天数程序

计算时间差我们原理是根据定义1、一年为360天,一个月为30天;2、代码中86400=24*60*60,代表一天中共有多少秒,这样就可以计算出来了

需要说明的是:1、定义一年为360天,一个月为30天;2、代码中86400=24*60*60,代表一天中共有多少秒;3、这两个时间都要规范的写成类似2013-07-28的形式;4、推广到所有的PHP程序,可以把Get_option('swt_builddate')这个wordpress获取后台数据的参数改成需要比较的时间参数,代码如下:

  1. <?php
  2. //Get detail gap of year,month and days between two different time by vfhky 20130728
  3. $common = (time()-strtotime(get_option('swt_builddate')));
  4. $a = floor($common/86400/360); //整数年
  5. $b = floor($common/86400/30) - $a*12; //整数月
  6. $c = floor($common/86400) - $a*360 - $b*30; //整数日
  7. $d = floor($common/86400); //总的天数
  8. echo $a."年".$b."月".$c."日(共计".$d."天)";
  9. ?>

其它的一些方法,代码如下:

  1. <?php
  2. function count_days($a,$b){
  3. $a_dt=getdate($a);
  4. $b_dt=getdate($b);
  5. $a_new=mktime(12,0,0,$a_dt['mon'],$a_dt['mday'],$a_dt['year']);
  6. $b_new=mktime(12,0,0,$b_dt['mon'],$b_dt['mday'],$b_dt['year']);
  7. return round(abs($a_new-$b_new)/86400);
  8. }
  9. //今天与2008年10月11日相差多少天
  10. $date1=strtotime(time());
  11. $date1=strtotime('10/11/2008');
  12. $result=count_days($date1,$date2);
  13. echo $result;
  14. ?>

例2,代码如下:

  1. <?php
  2. //今天与2008年9月9日相差多少天
  3. $Date_1=date("Y-m-d");
  4. $Date_2="2008-10-11";
  5. $d1=strtotime($Date_1);
  6. $d2=strtotime($Date_2);
  7. $Days=round(($d2-$d1)/3600/24);
  8. echo "今天与2008年10月11日相差".$Days."天";
  9. ?>

总结:从上面实例我们可以看得出来其实就是使用mktime与strtotime了,然后再通过计算出来的时间进行加减就得出来我们要的时间日期了。