编写一个函数,将某人的名字,姓氏,出生年份,月份和日期作为参数,并返回全名+年龄。确保app / programm在2015年或之后还提供正确的结果。检查前两个参数是否为字符串,三分之一是整数。
因为我是PHP的新手并且对日期一无所知(我用谷歌搜索但我无法理解它) 提前致谢! :) (自己写了一些代码试试,但它没用,所以我把它留了出来)
答案 0 :(得分:1)
<?php
function getAge($f_name, $l_name, $b_day, $b_month, $b_year) {
//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = $b_month . "/" . $b_day . "/" . $b_year;
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
return $f_name ." ". $l_name ." is: " . $age;
}
?>
答案 1 :(得分:0)
这是一个简单的功能
//birthday YYYY-MM-DD
function userInfo($fname, $lname, $birthday) {
//Calc age
$age = date_diff(date_create($birthday), date_create('today'))->y;
return $fname ." ". $lname . " ".$age;
}
现在称之为
echo userInfo('John', 'Doe', '1986-02-01');
答案 2 :(得分:0)
使用此功能
<?php
function get_the_user($fname, $lname,$m ,$d,$y)
$birthDate =$m.'/'.$d.'/'.$y;
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
echo "Age is:" . $age;
return $fname.' '.$lname.'is '.$age.' old';
?>
答案 3 :(得分:0)
您可以使用DateTime
类进行日期时间的简单操作。
function getAge($name, $surname, $b_year, $b_month, $b_date)
{
$today = new DateTime();
$birthdate = new DateTime($b_year . '-' . $b_month . '-' . $b_date);
$diff = $today->diff($birthdate);
return $name . ' ' . $surname . ' is ' . $diff->format('%y years') . ' old';
}
echo getAge('Mr.', 'Smith', 1990, 12, 12);
输出:
Mr. Smith is 23 years old
检查前两个参数是否为字符串,三分之一是整数。
我相信这对你来说不会有问题:)。
答案 4 :(得分:-1)
为什么不创建Person对象并创建一些方法来处理逻辑和格式。像:
class Person {
public $firstName, $lastName, $dob;
public function __construct($firstName, $lastName, $dob) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->dob = new DateTime($dob);
}
public function getFullname() {
return $firstName . ' ' . $lastName;
}
public function getAge($onDate=null) {
if ($onDate === null) $onDate = date('Y-m-d');
$onDate = new DateTime($onDate);
$ageOnDate = $this->dob->diff($onDate)->y;
return $ageOnDate;
}
}
$dude = new Person('John', 'Doe', '1980-01-15');
echo $dude->getFullName() . "\n";
echo $dude->getAge() . "\n"; // get his age today
echo $dude->getAge('2015-06-01'); // get his age on June 1st, 2015