ホームページ >バックエンド開発 >PHPチュートリアル >PHP で 2 つの日付間の月の差を計算する方法
PHP で 2 つの日付の差を計算するにはどうすればよいですか?
<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 />
<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 />