Reputation: 1247
I know the day of birth, lets say: 1996-12-12
I know that today is: 2014-11-12
Now I want to get the date of the last birthday. And I have written this solution, but I don't like the complexity of the code. How can I write it more readable for other programmers?
$lstrBirthday = '1996-12-12';
$lstrLastBirtday = (strtotime(date('Y').date('-m-d', strtotime($lstrBirthday))) > strtotime('now')) ? (date('Y') - 1).date('-m-d', strtotime($lstrBirthday)) : date('Y').date('-m-d', strtotime($lstrBirthday));
Thanks!
Upvotes: 1
Views: 222
Reputation: 27325
Its easier if you use the DateTime functions
$begin = new DateTime( '1996-12-12' );
$end = new DateTime();
$end = $end->modify( '-1 day' );
$interval = new DateInterval('P1Y');
$daterange = new DatePeriod($begin, $interval ,$end);
$bd = '';
foreach($daterange as $date){
$bd = $date->format("Ymd");
}
Edit: So now you have the last entry ;)
Something like that i can't test it now but you can foreach over the period. If the date is in the past you should get the last birthday. If you make +1 year
its in the future.
Edit: For @pascalvgemert perhaps its a bit more readable for you...
public function getLastBirthdate($startDate) {
$begin = new DateTime( $startDate );
$end = new DateTime();
$end = $end->modify( '-1 day' );
$interval = new DateInterval('P1Y');
$daterange = new DatePeriod($begin, $interval ,$end);
$bd = '';
foreach($daterange as $date){
$bd = $date->format("Ymd");
}
return $bd;
}
$lastBD = getLastBirthdate('1996-12-12');
Upvotes: 5