カレンダーの次の X 日を計算したいと思います。
たとえば、今日は 2012-10-08 です。X=25 の場合は 2012-10-25 を返したいのですが、X=06 の場合は 2012-11-06 を返します。月に必要な X 日がない場合は、その月の最後の日を返す必要があります (たとえば、2 月 30 日を探している場合、うるう年の場合は 28 または 29 を返す必要があります)。
単純に思えますが、すべての特殊なケース (年の最後の月、28 ~ 31 日の月など) に引っかかります。
カレンダーの次の X 日を計算したいと思います。
たとえば、今日は 2012-10-08 です。X=25 の場合は 2012-10-25 を返したいのですが、X=06 の場合は 2012-11-06 を返します。月に必要な X 日がない場合は、その月の最後の日を返す必要があります (たとえば、2 月 30 日を探している場合、うるう年の場合は 28 または 29 を返す必要があります)。
単純に思えますが、すべての特殊なケース (年の最後の月、28 ~ 31 日の月など) に引っかかります。
あなたは使用することができstrtotime()ますt:
$x = 5; // given day
if(date('t') < $x){ // check if last day of the month is lower then given day
$x = date('t'); // if yes, modify $x to last day of the month
}
$month = date('m'); // current month
if(date('d') >= $x){ // if $x day is now or has passed
$month = $month+1; // increase month by 1
}
$year = date('Y'); // current year
if($month > 12){ // if $month is greater than 12 as a result from previous if
$year = date('Y')+1; // increase year
$month = 1; // set month to January
}
if(date('t', strtotime($year.'-'.$month.'-01')) < $x){ // check if last day of the new month is lower then given day
$x = date('t', strtotime($year.'-'.$month.'-01')); // if yes, modify $x to last day of the new month
}
$date = date('d F Y', strtotime($year.'-'.$month.'-'.$x));
// 05 November 2012
HEREは素晴らしいチュートリアルです。