Bootstrap 日历没有相同的值

Bootstrap calendar doesn't gave the same value

在我的代码中,我试图检查用户的年龄是否超过 18 岁。 对于我的输入字段,我使用 bootstrap 日期输入。当我输入日期时,代码可以完美运行,但是当我使用日期选择器选择日期时,它总是 returns true。

这是我的函数:

$date = $_POST['birthdate'];
$orderdate = explode('-', $date);
$byr = $orderdate[0];
$bmon = $orderdate[1];
$bday = $orderdate[2];

function check21 ($bday, $bmon, $byr) {
    if (date('Y') - $byr > 18) { return true; } else {
        if (date('Y') - $byr = 18) { 
            if (date('m') - $bmon > 0) { return true; } else {
                if (date('m') - $bmon = 0) {
                    if (date('d') - $bday >= 0) { return true; }
                }
            }
        }
    }
    return false;
}

if (check21($bday, $bmon, $byr)) { 
    echo 'user is above 18';

} else { 
    echo 'user is not 18 years old'; 
}

这是我的日期输入字段:

<div class="form-group">
    <input type="date" name="birthdate" class="form-control input-mini login-input" required>
</div>

有人知道如何解决这个问题吗?

假设您使用的是 this plugin,请尝试在 javascript 上设置日期格式:

$(document).ready(function() {
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd'
    });
});

并且在服务器上您可以像这样改进您的代码:

<?php

$date = $_POST['birthdate'] ?? null; // do some validation if you want
$birthdate = DateTime::createFromFormat('Y-m-d', $date); // create a datetime instance, result will be false if $date has the wrong format

function check21($birthdate) {
    // check if the today date minus 18 years is prior to the birth date
    return $birthdate <= (new DateTime())->modify('-18 years');
}

if (check21($birthdate)) { 
    echo 'user is above 18';
} else { 
    echo 'user is not 18 years old'; 
}