PHP怎樣計算兩個日期相差幾個月?

來源:互聯網
上載者:User
 


以上代碼計算出相差13個月,不知道該怎麼改才能正常一些?


回複討論(解決方案)

去掉 abs
返回 -11 表示 2013-02-01 比 2014-01-01 少 11 個月
當然你也可以將整個傳回值 abs,但這樣就只是知道差 11 個月,但不知道是多了還是少了

function getMonthNum($date1,$date2){$date1_stamp=strtotime($date1);$date2_stamp=strtotime($date2);list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m']; } echo getMonthNum("2013-02-01","2014-01-01");echo getMonthNum("20130201","20140101");echo getMonthNum("201302","201401");

=$date2[0]){  return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);  }  else{  return abs($date2[0] - $date1[0]) * 12 - abs($date1[1] - $date2[1]);  } }echo getMonthNum("2013-02-01","2014-01-01",'-');?>

上面寫錯了。。。。。重發:

function getMonthNum($date1,$date2){$date1_stamp=strtotime($date1);$date2_stamp=strtotime($date2);list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));return abs(($date_2['y']-$date_1['y'])*12 +$date_2['m']-$date_1['m']); } echo getMonthNum("2013-02-01","2014-01-01");echo getMonthNum("20130201","20140101");echo getMonthNum("201302","201401");

function getMonthNum($date1,$date2){$date1_stamp=strtotime($date1);$date2_stamp=strtotime($date2);list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m']; } echo getMonthNum("2013-02-01","2014-01-01");echo getMonthNum("20130201","20140101");echo getMonthNum("201302","201401");

echo getMonthNum("2013-02-01","2012-01-01");//11
這對嗎?

$start_time = "2014-01-01";
$end_time = "2015-05-08";
for (;1==1;){
echo date("Y-m",strtotime($start_time))."
";
$end_time = date("Y-m",strtotime( $end_time ));

if($start_time==$end_time){
break;
}
$start_time = date("Y-m",strtotime("$start_time +1 month"));
}

function getMonthNum( $date1, $date2, $tags='-'){  $time1 = strtotime($date1);  $time2 = strtotime($date2);  $date1 = explode($tags,$date1);  $date2 = explode($tags,$date2);  $months =abs($date1[0]-$date2[0])*12;  if($time1 > $time2){return $months+$date1[1]-$date2[1];  }else{return -($months+$date2[1]-$date1[1]);  } }
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.