Heim  >  Artikel  >  Backend-Entwicklung  >  程序员 - PHP计算出两个年份的相差的月份,注意我只要月份,比如 "2013-07-03" "2014-03-12"

程序员 - PHP计算出两个年份的相差的月份,注意我只要月份,比如 "2013-07-03" "2014-03-12"

WBOY
WBOYOriginal
2016-06-06 20:46:411066Durchsuche

PHP计算出两个年份的相差的月份,注意我只要月份,比如 "2013-07-03" "2014-03-12",他们相差的8个月,那么你的函数中必须返回8,注意代码冗余

回复内容:

PHP计算出两个年份的相差的月份,注意我只要月份,比如 "2013-07-03" "2014-03-12",他们相差的8个月,那么你的函数中必须返回8,注意代码冗余

上一个回答没考虑年份差(不过题主强调了只需要月份),这里补上 @ 2014-03-27 10:06:25:

<code class="lang-php">$time_begin   = strtotime("2012-07-03");
$time_end     = strtotime("2014-03-12");
$time_differ  = $time_end - $time_begin;
$year_differ  = date('Y', $time_differ);
$month_differ = date('m', $time_differ);
$result       = 12*intval($year_differ-1970)+intval($month_differ)-1;
</code>

<code class="lang-php">$time_begin   = strtotime("2013-07-03");
$time_end     = strtotime("2014-03-12");
$time_differ  = $time_end - $time_begin;
$month_differ = date('m', $time_differ);
$result       = intval($month_differ)-1;
</code>

亲测可行。

<code>    $d1 = new DateTime('2013-07-03');
    $d2 = new DateTime('2014-03-12');
    $diff=$d2->diff($d1);
    echo ($diff->y*12)+$diff->m;
</code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn