How does PHP calculate the difference between two dates for several months?

Source: Internet
Author: User
Tags date1
How does PHP calculate the gap between two dates for several months? & Lt ;? Phpfunction & nbsp; getMonthNum (& nbsp; $ date1, & nbsp; $ date2, & nbsp; $ tags = '-' & nbsp;) {& nbsp; $ date1 & nbsp ;=& nbsp; explode ($ tags, $ date PHP how to calculate the gap between the two dates for several months?

function getMonthNum( $date1, $date2, $tags='-' ){
  $date1 = explode($tags,$date1);
  $date2 = explode($tags,$date2);
  return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
 }

echo getMonthNum("2013-02-01","2014-01-01",'-');

?>


The code above calculates a difference of 13 months. I don't know how to change it to be normal? Php date:
------ Solution --------------------
Remove abs
-11 indicates that is 11 months earlier
Of course, you can also return the entire abs value, but you only know that the difference is 11 months, but you do not know whether it is more or less.
------ Solution --------------------


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");


------ Solution --------------------

function getMonthNum( $date1, $date2, $tags='-' ){
  $date1 = explode($tags,$date1);
  $date2 = explode($tags,$date2);
  if ($date1[0]>=$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",'-');

?>


------ Solution --------------------
The above is wrong ..... Resend:



function getMonthNum($date1,$date2){

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.