1

ループ内で決まった回数だけ日付を月単位で繰り返そうとしています。日付が有効な日付である場合にのみ日付をエコーし​​、そうでない場合は日付をスキップします。たとえば、「2012-02-30 10:10:00」がループに入ってくる場合、それは無視されてスキップされ、次の反復に進みます。

以下のコードは、start_date "2011-11-07 10:15:00"に対しては正常に機能しますが、コメント付きのstart_date、つまり "2011-11-30 10:15:00"に変更すると、24時間後に追加されます。 1回の反復をスキップします。

どこが間違っているのかわかりません。

<?php
//$start_date = "2011-11-30 10:15:00";
$start_date = "2011-11-07 10:15:00";
$no_of_repeat = 15;
$repeat_timing = 0;
for($x=0; $x<$no_of_repeat; $x++) {
    $start_date = date('Y-m-d G:i:s',(strtotime($start_date) + ($repeat_timing)));
    if(date("m",strtotime($start_date)) != 12) {
        $next_month = date('m',strtotime($start_date)) + 1;
        $year = date('Y',strtotime($start_date));
    } else {
        $next_month = 1 ;
        $year = date('Y',strtotime($start_date)) + 1;
    }
    $day = date("d",strtotime($start_date));
    $next_date =
    $year."-".
    $next_month."-".
    $day." ".
    date("G",strtotime($start_date)).":".
    date("i",strtotime($start_date)).":".
    date("s",strtotime($start_date));
    if(checkdate($next_month,$day,$year))
        $repeat_timing = strtotime($next_date) - strtotime($start_date);
    else
        continue;   
    echo $next_date."<br />";
}
?>

コメントされたstart_dateの期待される結果は次のとおりです。

2011-12-30 10:15:00
2012-1-30 10:15:00
2012-3-30 10:15:00
2012-4-30 10:15:00
2012-5-30 10:15:00
2012-6-30 10:15:00
2012-7-30 10:15:00
2012-8-30 10:15:00
2012-9-30 10:15:00
2012-10-30 10:15:00
2012-11-30 10:15:00
2012-12-30 10:15:00
2013-1-30 10:15:00
4

3 に答える 3

0

次のことを試してください。

// starting variables
$startDate = "2011-11-30";
$time = '10:15:00';
$numberOfTimesToRepeat = 10;

// Set our counts to 0
$count = 0;
$datesFound = 0;

// parse date
list($startYear,$startMonth,$startDay) = explode('-',$startDate);

// Create an array
while ($datesFound < $numberOfTimesToRepeat) {

    // Calculate number of months to add
    $monthsToAdd = fmod($count,12);

    // Calculate new month number
    $newMonth = (($startMonth + $monthsToAdd) > 12) ? ($startMonth + $monthsToAdd - 12) : ($startMonth + $monthsToAdd);

    // Add the leading 0 if necessary   
    if ($newMonth < 10 && strlen($newMonth) < 2) $newMonth = '0'.$newMonth;

    // Calculate number of months to add
    $yearsToAdd = floor(($count/12));

    $newYear = $startYear + $yearsToAdd;

    if (checkdate($newMonth,$startDay,$newYear)) {
        $dates[] = $newYear.'-'.$newMonth.'-'.$startDay.' '.$time;
        $datesFound++;
    }

    // increase our count either way
    $count++;

}



// Show the dates
foreach ($dates as $date) {
    echo $date.'<br />';
}
于 2011-11-07T19:17:22.107 に答える
0

電話すると

 $start_date = date('Y-m-d G:i:s',(strtotime($start_date) + ($repeat_timing)));

日付に 1 か月を追加していますが、repeat_timing 変数も補正しています。2011 年 1 月 30 日の日付に 2678400 秒追加すると、およそ 2011 年 3 月 1 日になります。

月、日、年を日付変数とは別にして、手動で計算することをお勧めします。これにより、DATE が時間枠を変更するのを防ぐことができます。

于 2011-11-07T07:56:56.857 に答える