在PHP中查找月差异?

有什么办法find在PHP中的月份差异? 我有从2003年10月17日至2004年3月24日的input。 我需要找出这两天内有多less个月。 如果说6个月,我只需要几个月的产出。 感谢您指导我的一天差异。

我通过My​​SQLfind解决scheme,但我需要在PHP中。 任何人都可以帮助我,提前致谢。

这是一个快速的:

$date1 = mktime(0,0,0,10,0,2003); // mdy, use 0 for day $date2 = mktime(0,0,0,3,0,2004); // mdy, use 0 for day echo round(($date2-$date1) / 60 / 60 / 24 / 30); 

最简单的方法,而不是重新发明轮子。 这会给你完整的月份差异。 即以下两个date差不多是 76个月,但结果是75个月。

 date_default_timezone_set('Asia/Tokyo'); // you are required to set a timezone $date1 = new DateTime('2009-08-12'); $date2 = new DateTime('2003-04-14'); $diff = $date1->diff($date2); echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference"; 

在testing了大量的解决scheme之后,把所有的东西都放在一个unit testing中,这就是我所提出的:

 /** * Calculate the difference in months between two dates (v1 / 18.11.2013) * * @param \DateTime $date1 * @param \DateTime $date2 * @return int */ public static function diffInMonths(\DateTime $date1, \DateTime $date2) { $diff = $date1->diff($date2); $months = $diff->y * 12 + $diff->m + $diff->d / 30; return (int) round($months); } 

例如它将返回(unit testing中的testing用例):

  • 01.11.2013 – 30.11.2013 – 1个月
  • 01.01.2013 – 31.12.2013 – 12个月
  • 31.01.2011 – 28.02.2011 – 1个月
  • 01.09.2009 – 01.05.2010 – 8个月
  • 01.01.2013 – 31.03.2013 – 3个月
  • 15.02.2013 – 15.04.2013 – 2个月
  • 01.02.1985 – 31.12.2013 – 347个月

注意:由于四舍五入的原因,即使是半个月也会四舍五入,如果在某些情况下使用,可能会导致问题。 所以不要在这种情况下使用它,它会导致你的问题。

例如:

  • 2013年11月2日 – 2013年12月31日将返回2,而不是1(如预期)。

哇,解决问题的方法…这个版本怎么样:

 function monthsBetween($startDate, $endDate) { $retval = ""; // Assume YYYY-mm-dd - as is common MYSQL format $splitStart = explode('-', $startDate); $splitEnd = explode('-', $endDate); if (is_array($splitStart) && is_array($splitEnd)) { $difYears = $splitEnd[0] - $splitStart[0]; $difMonths = $splitEnd[1] - $splitStart[1]; $difDays = $splitEnd[2] - $splitStart[2]; $retval = ($difDays > 0) ? $difMonths : $difMonths - 1; $retval += $difYears * 12; } return $retval; } 

注意:与其他几个解决scheme不同,这不依赖于PHP 5.3中添加的date函数,因为许多共享主机还没有。

我只是想补充一点,如果有人正在寻找一个简单的解决scheme,计算每个触及的月份而不是完整的月份,四舍五入的月份或类似的东西。

 // Build example data $timeStart = strtotime("2003-10-17"); $timeEnd = strtotime("2004-03-24"); // Adding current month + all months in each passed year $numMonths = 1 + (date("Y",$timeEnd)-date("Y",$timeStart))*12; // Add/subtract month difference $numMonths += date("m",$timeEnd)-date("m",$timeStart); echo $numMonths; 

http://www.php.net/manual/en/datetime.diff.php

这将返回具有格式方法的DateInterval对象。

 $datetime1 = date_create('2009-10-11'); $datetime2 = date_create('2013-1-13'); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%a day %m month %y year'); 
 <?php # end date is 2008 Oct. 11 00:00:00 $_endDate = mktime(0,0,0,11,10,2008); # begin date is 2007 May 31 13:26:26 $_beginDate = mktime(13,26,26,05,31,2007); $timestamp_diff= $_endDate-$_beginDate +1 ; # how many days between those two date $days_diff = $timestamp_diff/2635200; ?> 

参考: http : //au.php.net/manual/en/function.mktime.php#86916

 function monthsDif($start, $end) { // Assume YYYY-mm-dd - as is common MYSQL format $splitStart = explode('-', $start); $splitEnd = explode('-', $end); if (is_array($splitStart) && is_array($splitEnd)) { $startYear = $splitStart[0]; $startMonth = $splitStart[1]; $endYear = $splitEnd[0]; $endMonth = $splitEnd[1]; $difYears = $endYear - $startYear; $difMonth = $endMonth - $startMonth; if (0 == $difYears && 0 == $difMonth) { // month and year are same return 0; } else if (0 == $difYears && $difMonth > 0) { // same year, dif months return $difMonth; } else if (1 == $difYears) { $startToEnd = 13 - $startMonth; // months remaining in start year(13 to include final month return ($startToEnd + $endMonth); // above + end month date } else if ($difYears > 1) { $startToEnd = 13 - $startMonth; // months remaining in start year $yearsRemaing = $difYears - 2; // minus the years of the start and the end year $remainingMonths = 12 * $yearsRemaing; // tally up remaining months $totalMonths = $startToEnd + $remainingMonths + $endMonth; // Monthsleft + full years in between + months of last year return $totalMonths; } } else { return false; } } 
 // get year and month difference $a1 = '20170401'; $a2 = '20160101' $yearDiff = (substr($a1, 0, 4) - substr($a2, 0, 4)); $monthDiff = (substr($a1, 4, 2) - substr($a2, 4, 2)); $fullMonthDiff = ($yearDiff * 12) + $monthDiff; // fullMonthDiff = 16 

这是我的增强版本的@deceze回答:

  /** * @param string $startDate * Current date is considered if empty string is passed * @param string $endDate * Current date is considered if empty string is passed * @param bool $unsigned * If $unsigned is true, difference is always positive, otherwise the difference might be negative * @return int */ public static function diffInFullMonths($startDate, $endDate, $unsigned = false) { $diff = (new DateTime($startDate))->diff(new DateTime($endDate)); $reverse = $unsigned === true ? '' : '%r'; return ((int) $diff->format("{$reverse}%y") * 12) + ((int) $diff->format("{$reverse}%m")); } 

最好的办法。

 function getIntervals(DateTime $from, DateTime $to) { $intervals = []; $startDate = $from->modify('first day of this month'); $endDate = $to->modify('last day of this month'); while($startDate < $endDate){ $firstDay = $startDate->format('Ymd H:i:s'); $startDate->modify('last day of this month')->modify('+1 day'); $intervals[] = [ 'firstDay' => $firstDay, 'lastDay' => $startDate->modify('-1 second')->format('Ymd H:i:s'), ]; $startDate->modify('+1 second'); } return $intervals; } $dateTimeFirst = new \DateTime('2013-01-01'); $dateTimeSecond = new \DateTime('2013-03-31'); $interval = getIntervals($dateTimeFirst, $dateTimeSecond); print_r($interval); 

结果:

 Array ( [0] => Array ( [firstDay] => 2013-01-01 00:00:00 [lastDay] => 2013-01-31 23:59:59 ) [1] => Array ( [firstDay] => 2013-02-01 00:00:00 [lastDay] => 2013-02-28 23:59:59 ) [2] => Array ( [firstDay] => 2013-03-01 00:00:00 [lastDay] => 2013-03-31 23:59:59 ) ) 

在我的情况下,我需要计算完整的月份和一天的剩菜作为月份,以及build立一个折线图标签。

 /** * Calculate the difference in months between two dates * * @param \DateTime $from * @param \DateTime $to * @return int */ public static function diffInMonths(\DateTime $from, \DateTime $to) { // Count months from year and month diff $diff = $to->diff($from)->format('%y') * 12 + $to->diff($from)->format('%m'); // If there is some day leftover, count it as the full month if ($to->diff($from)->format('%d') > 0) $diff++; // The month count isn't still right in some cases. This covers it. if ($from->format('d') >= $to->format('d')) $diff++; }