PHP strtotime 下个月的第一天什么也不返回


php strtotime first day of next month returns nothing

我一直在阅读有关php中strtotime和"下个月"问题的问题。我想做的是两个日期之间的月份计数器。例如,如果我的开始日期为 01.02.2012 和停止日期为 07.04.2012,我想获得返回值 - 3 个月。如果开始日期 i 28.02.2012 和 07.04.2012,结果也将是 3 个月。我没有计算确切的天数/月数,只是两个日期之间的几个月。用一些奇怪的日期、mktime 和 strtotime 用法来制作它没什么大不了的,但不幸的是,开始和停止日期可能在两个不同的年份,所以

mktime(0,0,0,date('m')+1,1,date('Y');

不会工作(我现在不知道年份,如果它在开始和停止日期之间发生变化。 我可以计算它,但这不是很好的解决方案)。完美的解决方案是使用:

$stat = Array('02.01.2012', '07.04.2012')
$cursor = strtotime($stat[0]);
$stop = strtotime($stat[1]);
$counter = 0;
    while ( $cursor < $stop ) {
   $cursor = strtotime("first day of next month", $cursor);
   echo $cursor . '<br>';
   $counter++;
   if ( $counter > 100) { break; } // safety break;
    }
    echo $counter . '<br>';

不幸的是,strtotime 没有返回正确的值。如果我使用它,则返回空字符串。任何想法如何获取下个月第一天的时间戳?

溶液

$stat = Array('02.01.2012', '01.04.2012');
$start = new DateTime( $stat[0] );
$stop = new DateTime( $stat[1] );
while ( $start->format( 'U') <= $stop->format( 'U' ) ) {
    $counter ++;
    echo $start->format('d:m:Y') . '<br>';
    $start->modify( 'first day of next month' );
}
echo '::' . $counter . '..<br>';
<?php
$stat = Array('02.01.2012', '07.04.2012');
$stop = strtotime($stat[1]);
list($d, $m, $y) = explode('.', $stat[0]);
$count = 0;
while (true) {
    $m++;
    $cursor = mktime(0, 0, 0, $m, $d, $y);
    if ($cursor < $stop) $count ++; else exit;
}
echo $count;
?>

简单的方法:D