只是想知道,我可以这样做,以验证用户输入的日期超过 18?
//Validate for users over 18 only
function time($then, $min)
{
$then = strtotime('March 23, 1988');
//The age to be over, over +18
$min = strtotime('+18 years', $then);
echo $min;
if (time() < $min) {
die('Not 18');
}
}
只是偶然发现了这个函数 date_diff:http://www.php.net/manual/en/function.date-diff.php看起来,更有希望。
26
对我来说唯一的问题是用户界面-如何优雅地向用户发送错误消息。
另一方面,您的功能可能无常工作,因为您没有获得适当的生日(您使用的是固定生日)。您应该将“1988 年 3 月 23 日”更改为 $
//Validate for users over 18 only
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
//The age to be over, over +18
$min = strtotime('+18 years', $then);
echo $min;
if(time() < $min) {
die('Not 18');
}
}
或者你可以:
// validate birthday
function validateAge($birthday, $age = 18)
{
// $birthday can be UNIX_TIMESTAMP or just a string-date.
if(is_string($birthday)) {
$birthday = strtotime($birthday);
}
// check
// 31536000 is the number of seconds in a 365 days year.
if(time() - $birthday < $age * 31536000) {
return false;
}
return true;
}
20
这是我在多伦多用于银行系统的简化摘录,考虑到 366 天的闰年,这总是非常有效。
/* $dob is date of birth in format 1980-02-21 or 21 Feb 1980
* time() is current server unixtime
* We convert $dob into unixtime, add 18 years, and check it against server's
* current time to validate age of under 18
*/
if (time() < strtotime('+18 years', strtotime($dob))) {
echo ' is under 18 years of age.';
exit;
}
7
我认为最好使用 DateTime 类。
$bday = new DateTime("22-10-1993");
$bday->add(new DateInterval("P18Y")); //adds time interval of 18 years to bday
//compare the added years to the current date
if($bday < new DateTime()){
echo "over 18";
}else{
echo "below 18";
}
DateTime::diff 还可用于将日期与当前日期进行比较。
$today = new DateTime(date("Y-m-d"));
$bday = new DateTime("22-10-1993");
$interval = $today->diff($bday);
if(intval($interval->y) > 18){
echo "older than 18";
}else{
echo "younger than 18";
}
N / B:1)对于第二种方法,如果 $bday 大于 $今天 18 年或更长时间,它将返回更旧,因此请确保输入的日期小于 $今天。2)DateTime 适用于 php 5.2.0 及以上
2
if( strtotime("1988/03/23") < (time() - (18 * 60 * 60 * 24 * 365))) {
print "yes";
} else {
print "no";
}
...然而,不占飞跃年
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(30条)