我的数据库包含'birthdate'列,用户可以用“Y-m-d”格式填充。
现在我想要回复希望用户生日快乐的总天数。
E.g。如果当前日期是2014-06-06并且用户出生日期是1980-06-26,那么生日即将到来6月26日,代码应该回应“生日是在20天后”
我试过的是跟随 -
$date1= date("m-d");
$date2=date("m-d",strtotime($data['birthdate']));
$dateDiff = abs(strtotime($date2) - strtotime($date1));
$remainedDays = floor($dateDiff/(60*60*24));
echo "Birthday Is After $remainedDays Days";
但是这段代码给了0天
答案 0 :(得分:3)
执行此操作的最简单方法是DateTime classes,特别是DateTime::diff method。请注意,您应该确保每个日期的时间是午夜,然后测试今年的生日是否已经发生。
<?php
$birthday = "1980-06-24";
// get date of birthday this calendar year
$parts = explode('-', $birthday, 2);
$birth_date = new DateTime(date('Y') . '-' . $parts[1] .' 00:00:00');
$today = new DateTime('midnight today');
if ($birth_date < $today) {
// next birthday is in one year
$birth_date->modify("+1 Year");
}
// get number of days days remaining
$diff = $birth_date->diff($today);
if ($diff->days > 0) {
echo "There are " . $diff->days . " remaining until your birthday.";
} else {
echo "Happy birthday!";
}
答案 1 :(得分:0)
这是一个可用于即将到来的B'days的算法。这也将考虑闰年,B'day为02/29
您可以根据需要修改代码。它将检查已经过期的即将到来的B'day或B'day。
$bday = new DateTime("1980-06-26");
$today = new DateTime();
$b_y = $bday->format('Y');
$b_d = $bday->format('d');
$b_m = $bday->format('m');
if((bool)$bday->format('L') && $b_d == 29 && $b_m == 2){
if((bool)$today->format('L')){
$bday_obj = new DateTime(date('Y').'-'.$b_m.'-'.$b_d);
$diff = $bday_obj->diff($today);
}else{
for($i=1;$i++;$i<=3){
$today->add(new DateInterval('P1Y'));
if((bool)$today->format('L')){
$bday_obj = new DateTime(date('Y').'-'.$b_m.'-'.$b_d);
$diff = $bday_obj->diff($today);
break ;
}
}
}
}else{
$bday_obj = new DateTime(date('Y').'-'.$b_m.'-'.$b_d);
$diff = $bday_obj->diff($today);
}
$now = new DateTime() ;
if($now > $bday_obj){
echo 'Your birthday was over '.$diff->format('%a days').' before';
}else{
echo 'Your birthday is after '.$diff->format('%a days');
}