最简单的什么是最有效的方式来获得下一个生日日期我有出生日期,如' 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;
}
效率不高(如果日期过去很多,则递归过多)。
我希望有一个解决方案,我可以轻松更改$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
答案 0 :(得分:2)
使用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');
答案 1 :(得分:0)
感谢@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;
}