douzhao1912 2014-11-12 10:38
浏览 53
已采纳

如何编写整洁的代码来获取上一个生日日期?

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!

  • 写回答

1条回答 默认 最新

  • dongsanhu4784 2014-11-12 10:47
    关注

    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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?