从PHP中已知的日期获取下一个即将到来的生日


Get next upcoming birthday from known date in PHP

当我有像'1983-08-15'这样的出生日期时,获得下一个生日日期的

最简单最有效的方法是什么

目前我对strtotime()

做了类似的操作
function get_next_date($start_timestamp, $interval = 1, $time_frame = 'year'){
                                //+1 year
    $nextdate = strtotime('+'.$interval.' '.$time_frame, $start_timestamp);
       //date is still in the past
    if($nextdate - time() < 0){
         return get_next_date($nextdate);
    }
    return $nextdate;
}

效率不高(如果date是很久以前的事,递归会太多)。

我想有一个解决方案,我可以很容易地改变$interval$time_frame

编辑:

建议的解决方案strtotime(date('d-M-', $start_timestamp).date('Y')." +{$interval} {$time_frame}")不工作:

//(assuming today is the 2014-07-22)
1983-03-01 => 2015-03-01  //OK
1983-08-01 => 2015-08-01  //FALSE, should be 2014-08-01

函数还应该接受每10个生日的不同间隔,例如:

1983-03-01 => 2023-03-01
1984-08-01 => 2014-08-01

使用DateTime类的另一种方法:

function get_next_birthday($birthday) {
    $date = new DateTime($birthday);
    $date->modify('+' . date('Y') - $date->format('Y') . ' years');
    if($date < new DateTime()) {
        $date->modify('+1 year');
    }
    return $date->format('Y-m-d');
}
echo get_next_birthday('1983-08-15');

感谢@JonathanKuhn我做了这个函数:

function get_next_date($starttime, $interval, $time_frame) {
    $now = time();
    //based on the timeframe get the amount since the $startdate
    switch ($time_frame) {
        case 'year':
            $count = date('Y', $now)-date('Y', $starttime);
            break;
        case 'month':
            $count = abs((date('Y', $now) - date('Y', $starttime))*12 + (date('m', $now) - date('m', $starttime)));
            break;
        case 'week':
            $count = floor((abs($now - $starttime)/86400)/7);
            break;
        case 'day':
            $count = floor(abs($now - $starttime)/86400);
            break;
        default:
            //if you have other time frames you should add them here
            $count = $interval;
            break;
    }
    //how often the interval should get multipled
    $times = ceil($count/$interval);
    //get the next date by counting from the starting date up until $now with the calculated interval
    $nextdate = strtotime(date('d-M-Y', $starttime)." +".($interval*$times)." {$time_frame}");
    //date is maybe in the past (but in the same year, month or week)
    if($nextdate - $now < 0){
        //add an additional interval to the expression
        $nextdate = strtotime(date('d-M-Y', $starttime)." +".($interval*$times+$interval)." {$time_frame}");
    }
    return $nextdate;
}