1

strtotime と「来月」の問題に関する php の問題について読んでいます。私が作りたいのは、2つの日付の間の月のカウンターです。たとえば、開始日が 01.02.2012 で終了日が 07.04.2012 の場合、戻り値 - 3 か月を取得したいと思います。また、開始日が 2012 年 2 月 28 日と 2012 年 4 月 7 日の場合、結果は 3 か月になります。正確な日数/月数を数えているわけではなく、2 つの日付の間の月数を数えているだけです。奇妙な日付、mktime、および strtotime の使用法で作成することは大したことではありませんが、残念ながら開始日と終了日が 2 つの異なる年になる可能性があるため、

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>';
4

1 に答える 1

0
<?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

于 2012-04-07T14:44:02.520 に答える