我正在尝试根据日历日期范围计算每月定期发生的事件。February (28 days)
但是,当事件发生在本月 29 日时,我偶然发现了一个计算问题。希望一些专家可以给我一些指示,因为我试图在没有帮助的情况下四处寻找。
我已经包含了以下代码,以便于直接作为脚本运行。该January
范围工作正常,这给了我 2 个落在该范围内的日期:
// JANUARY 2013 Range (Working)
2012-12-29
2013-01-29
但如果您取消注释二月范围,它开始输出:
2013-01-29 // This is correct
2013-02-28 // This is the date which I want to ignore because its not on the 29th.
如果你取消注释April
范围,它开始什么都不输出。它应该输出一个日期,即2013-04-29
. 因此,我认为问题在于 2 月的计算。
<?php
// Start Calendar Range
// JANUARY 2013 Range (Working)
$rangeStart = new DateTime( '2012-12-30' );
$rangeEnd = new DateTime( '2013-02-03' );
// FEBRUARY 2013 Range (Not Working)
//$rangeStart = new DateTime( '2013-01-27' );
//$rangeEnd = new DateTime( '2013-03-03' );
// APRIL 2013 Range (Not Working)
//$rangeStart = new DateTime( '2013-03-31' );
//$rangeEnd = new DateTime( '2013-04-05' );
// MAY 2013 Range (Working)
//$rangeStart = new DateTime( '2013-04-28' );
//$rangeEnd = new DateTime( '2013-06-02' );
// Event date start
$eventStart = new DateTime( '2012-10-29' );
$recurTimes = 1;
// Loop thru the days of month
while( $rangeStart->format('U') <= $rangeEnd->format('U') ) {
$currView = mktime( 0, 0, 0, $rangeStart->format('m'), $eventStart->format('d'), $rangeStart->format('Y') );
$interval = round(($currView-$eventStart->format('U')) / 60 / 60 / 24 / 30);
$monthsAway = $eventStart->format('m')+$interval;
$recurMonth = $eventStart->format('m')%$recurTimes;
if( $monthsAway%$recurTimes == $recurMonth ) {
$nextRecur = getNextRecur( $eventStart->format('U'), $interval );
echo date( 'Y-m-d', $nextRecur ) . '<br />';
}
$rangeStart->modify('+1 month');
}
// function to add 1 month with leap year in consideration
function getNextRecur( $baseTime=null, $months=1 ) {
if( is_null( $baseTime ) ) $baseTime = time( );
$xMonths = strtotime( '+' . $months . ' months', $baseTime );
$before = (int)date( 'm', $baseTime )+12*(int)date( 'Y', $baseTime );
$after = (int)date( 'm', $xMonths )+12*(int)date( 'Y', $xMonths );
if( $after > $months+$before ) {
$xMonths = strtotime( date('Ym01His', $xMonths) . ' -1 day' );
}
return $xMonths;
}
?>