dqd82461 2014-06-17 12:07 采纳率: 0%
浏览 71
已采纳

如何在今天的PHP日期考虑年龄至少为18岁的人? [重复]

This question already has an answer here:

I've following code to check whether the user is born before today's date(the user date of birth is stored in a variable $form_data['dob']). The code for it is as below:

    if(change_date_format_to_db($form_data['dob'], 'Y-m-d') > change_date_format_to_db(date('Y-m-d'), 'Y-m-d'))
$this->mValidator->push_error($errors_msgs['user_dob_greater'], 'dob');

function change_date_format_to_db( $date, $current_format, $seperator = "/" ) { 
            if ( empty($date) || empty($current_format) ) {
                return "";
            }
            $current_format = strtoupper($current_format);
            $format_array   = explode("-", $current_format);
            $date_values    = explode($seperator, $date);

            for ($i=0;$i<3;$i++) {
                $date_data[ $format_array[$i] ] =  $date_values[$i] ;
            }

            $mysql_date_format = $date_data["Y"]."-".$date_data["M"]."-".$date_data["D"];
            return $mysql_date_format;
      }

Now instead of checking the user's date before today's date I want the user should be minimum 18 years old on today's date. How should I do this with above code? Thanks in advance.

</div>
  • 写回答

1条回答 默认 最新

  • duanfen2349 2014-06-17 12:16
    关注

    Keep it simple with DateTime Object

    $birthday = DateTime::createFromFormat('Y/m/d', $form_data['dob']);
    
    $diff = $birthday->diff(new DateTime());
    //                       ^^ now
    
    if ($diff->y < 18) {
        echo 'this site requires +18yrs';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?