首页 >后端开发 >php教程 >PHP怎么计算两个日期相差几个月

PHP怎么计算两个日期相差几个月

WBOY
WBOY原创
2016-06-13 12:17:372339浏览

PHP怎样计算两个日期相差几个月?

<br /><?php<br />function getMonthNum( $date1, $date2, $tags='-' ){<br />  $date1 = explode($tags,$date1);<br />  $date2 = explode($tags,$date2);<br />  return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);<br /> }<br /><br />echo getMonthNum("2013-02-01","2014-01-01",'-');<br /><br />?><br />


以上代码计算出相差13个月,不知道该怎么改才能正常一些?
------解决思路----------------------
去掉 abs
返回 -11 表示 2013-02-01 比 2014-01-01 少 11 个月
当然你也可以将整个返回值 abs,但这样就只是知道差 11 个月,但不知道是多了还是少了
------解决思路----------------------
<br /><br />function getMonthNum($date1,$date2){<br />	$date1_stamp=strtotime($date1);<br />	$date2_stamp=strtotime($date2);<br />	list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));<br />	list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));<br />	return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m'];<br /> }<br /> <br />echo getMonthNum("2013-02-01","2014-01-01");<br /><br />echo getMonthNum("20130201","20140101");<br /><br />echo getMonthNum("201302","201401");<br /><br />

------解决思路----------------------
<br /><?php<br />function getMonthNum( $date1, $date2, $tags='-' ){<br />  $date1 = explode($tags,$date1);<br />  $date2 = explode($tags,$date2);<br />  if ($date1[0]>=$date2[0]){<br />  return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);<br />  }<br />  else{<br />  return abs($date2[0] - $date1[0]) * 12 - abs($date1[1] - $date2[1]);<br />  }<br /> }<br /><br />echo getMonthNum("2013-02-01","2014-01-01",'-');<br /><br />?><br /><br />

------解决思路----------------------
上面写错了。。。。。重发:

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn