php 获得两个日期之间月份数的优雅方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4233605/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:21:41  来源:igfitidea点击:

Elegant way to get the count of months between two dates?

phpdate

提问by Simon

Let's assume i have two dates in variables, like

让我们假设我在变量中有两个日期,比如

$date1 = "2009-09-01";
$date2 = "2010-05-01";

I need to get the count of months between $date2and $date1($date2 >= $date1). I.e. i need to get 8.

我需要得到$date2$date1( $date2 >= $date1)之间的月数。即我需要得到8

Is there a way to get it by using datefunction, or i have to explode my strings and do some calculations?

有没有办法通过使用日期函数来获得它,或者我必须分解我的字符串并进行一些计算?

Thanks much

非常感谢

回答by Vincent Savard

For PHP >= 5.3

对于 PHP >= 5.3

$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");

var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)

DateTime::diff returns a DateIntervalobject

DateTime::diff 返回一个DateInterval对象

If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :

如果您不使用 PHP 5.3 或更高版本运行,我想您将不得不使用 unix 时间戳:

$d1 = "2009-09-01";
$d2 = "2010-05-01";

echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8

But it's not very precise (there isn't always 30 days per month).

但它不是很精确(每个月并不总是 30 天)。

Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.

最后一件事:如果这些日期来自您的数据库,那么使用您的 DBMS 来完成这项工作,而不是 PHP。

Edit:This code should be more precise if you can't use DateTime::diff or your RDBMS :

编辑:如果您不能使用 DateTime::diff 或您的 RDBMS ,则此代码应该更精确:

$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;

while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
    $i++;
}
echo $i; // 8

回答by Chuck Burgess

Or, if you want the procedural style:

或者,如果您想要程序风格:

$date1 = new DateTime("2009-09-01");
$date2 = new DateTime("2010-05-01");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';

UPDATE: Added the bit of code to account for the years.

更新:添加了一些代码来说明这些年。

回答by Mic

Or a simple calculation would give :

或者一个简单的计算会给出:

$numberOfMonths = abs((date('Y', $endDate) - date('Y', $startDate))*12 + (date('m', $endDate) - date('m', $startDate)))+1;

Accurate and works in all cases.

准确,适用于所有情况。

回答by Jesus Velazquez

This is another way to get the number of months between two dates:

这是获取两个日期之间的月数的另一种方法:

// Set dates
$dateIni = '2014-07-01';
$dateFin = '2016-07-01';

// Get year and month of initial date (From)
$yearIni = date("Y", strtotime($dateIni));
$monthIni = date("m", strtotime($dateIni));

// Get year an month of finish date (To)
$yearFin = date("Y", strtotime($dateFin));
$monthFin = date("m", strtotime($dateFin));

// Checking if both dates are some year

if ($yearIni == $yearFin) {
   $numberOfMonths = ($monthFin-$monthIni) + 1;
} else {
   $numberOfMonths = ((($yearFin - $yearIni) * 12) - $monthIni) + 1 + $monthFin;
}

回答by manix

I use this:

我用这个:

$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-09-01");
$months = 0;

$d1->add(new \DateInterval('P1M'));
while ($d1 <= $d2){
    $months ++;
    $d1->add(new \DateInterval('P1M'));
}

print_r($months);

回答by pollux1er

This is a simple method I wrote in my class to count the number of months involved into two given dates :

这是我在课堂上编写的一个简单方法,用于计算两个给定日期所涉及的月数:

public function nb_mois($date1, $date2)
{
    $begin = new DateTime( $date1 );
    $end = new DateTime( $date2 );
    $end = $end->modify( '+1 month' );

    $interval = DateInterval::createFromDateString('1 month');

    $period = new DatePeriod($begin, $interval, $end);
    $counter = 0;
    foreach($period as $dt) {
        $counter++;
    }

    return $counter;
}

回答by pathfinder

Using DateTime, this will give you a more accurate solution for any amount of months:

使用 DateTime,这将为您提供任何月份的更准确的解决方案:

$d1 = new DateTime("2011-05-14");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$d4 = ($d3->y*12)+$d3->m;
echo $d4;

You would still need to handle the leftover days $d3->dif your real world problem is not as simple and cut and dry as the original question where both dates are on the first of the month.

$d3->d如果您的现实世界问题不像最初的问题那样简单,那么您仍然需要处理剩余的日子,因为两个日期都在一个月的第一天。

回答by radhason power

I have used this and works in all conditions

我已经使用了它并且在所有条件下都可以使用

$fiscal_year = mysql_fetch_row(mysql_query("SELECT begin,end,closed FROM fiscal_year WHERE id = '2'"));


            $date1 = $fiscal_year['begin'];
            $date2 = $fiscal_year['end'];

            $ts1 = strtotime($date1);
            $ts2 = strtotime($date2);


            $te=date('m',$ts2-$ts1);

            echo $te;

回答by Poly

In case the dates are part of a resultset from a mySQL query, it is much easier to use the TIMESTAMPDIFF function for your date calculations and you can specify return units eg. Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name

如果日期是来自 mySQL 查询的结果集的一部分,则使用 TIMESTAMPDIFF 函数进行日期计算要容易得多,并且您可以指定返回单位,例如。 Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name

回答by Claudio

strtotime is not very precise, it makes an approximate count, it does not take into account the actual days of the month.

strtotime 不是很精确,它是一个近似计数,它没有考虑一个月的实际天数。

it's better to bring the dates to a day that is always present in every month.

最好将日期设置为每个月始终存在的一天。

$date1 = "2009-09-01";
$date2 = "2010-05-01";

$d1 = mktime(0, 0, 1, date('m', strtotime($date1)), 1, date('Y', strtotime($date1)));
$d2 = mktime(0, 0, 1, date('m', strtotime($date2)), 1, date('Y', strtotime($date2)));

 $total_month = 0;
 while (($d1 = strtotime("+1 MONTH", $d1)) <= $d2) {
     $total_month++;
 }
echo $total_month;