PHP日期问题


PHP Date issues

我有个问题。我正试图找出这个问题的答案,但我似乎无法集中注意力。希望有人能帮助我。问题是:

编写一个函数,以某人的名字、姓氏、出生年份、月份和日期为自变量,并返回全名+年龄。确保应用程序/程序在2015年或以后也会返回正确的结果。检查前两个参数是否为字符串,三分之一是否为整数。

由于我是PHP新手,对日期一无所知(我在谷歌上搜索了一下,但我无法将注意力集中在它上)提前感谢!:)(我自己写了一些代码尝试,但没用,所以我把它省略了)

<?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;
}
?>

这里有一个简单的函数来完成

//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');

使用此函数

<?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';
    ?>

您可以使用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

实时预览


检查前两个参数是否为字符串,三分之一是否为整数。

我相信这对你来说不会有问题:)。

有用的资源:

  • http://php.net/manual/en/function.gettype.php
  • http://php.net/manual/en/ref.var.php

为什么不创建一个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