php 在php中找到月份差异?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2681548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find Month difference in php?
提问by Karthik
Is there any way to find the month difference in PHP? I have the input of from-date 2003-10-17 and to-date 2004-03-24. I need to find how many months there are within these two days. Say if 6 months, I need the output in months only. Thanks for guiding me for day difference.
有没有办法在PHP中找到月差?我有从 2003-10-17 到 2004-03-24 的输入。我需要找出这两天有多少个月。假设 6 个月,我只需要几个月的输出。感谢您指导我的天差。
I find the solution through MySQL but I need it in PHP. Anyone help me, Thanks in advance.
我通过 MySQL 找到了解决方案,但我需要在 PHP 中使用它。任何人都可以帮助我,提前致谢。
采纳答案by Tower
Here's a quick one:
这是一个快速的:
$date1 = mktime(0,0,0,10,0,2003); // m d y, use 0 for day
$date2 = mktime(0,0,0,3,0,2004); // m d y, use 0 for day
echo round(($date2-$date1) / 60 / 60 / 24 / 30);
回答by deceze
The easiest way without reinventing the wheel. This'll give you the fullmonths difference. I.e. the below two dates are almost76 months apart, but the result is 75 months.
无需重新发明轮子的最简单方法。这会给你整月的差异。即下面的两个日期几乎相差 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";
回答by Valentin Despa
After testing tons of solutions, putting all in a unit test, this is what I come out with:
在测试了大量解决方案后,将所有解决方案放在单元测试中,这就是我得出的结论:
/**
* 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);
}
For example it will return (test cases from the unit test):
例如它将返回(来自单元测试的测试用例):
- 01.11.2013 - 30.11.2013 - 1 month
- 01.01.2013 - 31.12.2013 - 12 months
- 31.01.2011 - 28.02.2011 - 1 month
- 01.09.2009 - 01.05.2010 - 8 months
- 01.01.2013 - 31.03.2013 - 3 months
- 15.02.2013 - 15.04.2013 - 2 months
- 01.02.1985 - 31.12.2013 - 347 months
- 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 个月
Notice: Because of the rounding it does with the days, even a half of a month will be rounded, which may lead to issue if you use it with some cases. So DO NOT USE it for such cases, it will cause you issues.
注意:由于是四舍五入,所以即使是半个月也会四舍五入,在某些情况下使用可能会出现问题。所以不要在这种情况下使用它,它会给你带来问题。
For example:
例如:
- 02.11.2013 - 31.12.2013 will return 2, not 1 (as expected).
- 02.11.2013 - 31.12.2013 将返回 2,而不是 1(如预期)。
回答by MaX
I just wanted to add this if anyone is looking for a simple solution that counts each touched-upon month in stead of complete months, rounded months or something like that.
如果有人正在寻找一个简单的解决方案来计算每个触及的月份而不是完整的月份、四舍五入的月份或类似的东西,我只是想添加这个。
// 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;
回答by CLWill
Wow, way to overthink the problem... How about this version:
哇,过度思考问题的方式......这个版本怎么样:
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;
}
NB: unlike several of the other solutions, this doesn't depend on the date functions added in PHP 5.3, since many shared hosts aren't there yet.
注意:与其他几种解决方案不同,这不依赖于 PHP 5.3 中添加的日期函数,因为许多共享主机尚不存在。
回答by graydot
http://www.php.net/manual/en/datetime.diff.php
http://www.php.net/manual/en/datetime.diff.php
This returns a DateInterval object which has a format method.
这将返回一个具有格式方法的 DateInterval 对象。
回答by Stefan G. Beck
// 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
回答by Ehsan
This is my enhanced version of @deceze answer:
这是我对@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"));
}
回答by Lebnik
The best way.
最好的方法。
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('Y-m-d H:i:s');
$startDate->modify('last day of this month')->modify('+1 day');
$intervals[] = [
'firstDay' => $firstDay,
'lastDay' => $startDate->modify('-1 second')->format('Y-m-d 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);
Result:
结果:
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
)
)
回答by John Linhart
In my case I needed to count full months and day leftovers as month as well to build a line chart labels.
在我的情况下,我需要将整月和一天的剩余时间计算为月份,以构建折线图标签。
/**
* 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++;
}
回答by Siddharth Shukla
$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');

