从MySQL数据库获取的年龄计算

时间:2015-12-01 08:40:25

标签: php mysql

我正在尝试使用this年龄计算器来计算用户'年龄,存储在MySQL数据库中。我认为这会起作用,但似乎并没有。

我的问题是,我不知道如何从MySQL的用户表中获取日期。

<?php
require_once 'core/init.php';

$user = new User();

if(!$user->isLoggedIn()) {
    Redirect::to('index.php');
}

  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "<?php escape($user->data()->birthday); ?>";        //"08/13/2000";
  //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;
?>

1 个答案:

答案 0 :(得分:1)

我刚刚编写了这个使用DateTime类和相关方法的简单类 - 应该很容易使日期字符串适应正确的格式。

    class userage{

        private $dob;
        private $options;

        public function __construct( $dob=false, $options=array() ){
            $this->dob=$dob;
            $this->options=(object)array_merge( array(
                'timezone'  =>  'Europe/London',
                'format'    =>  'Y-m-d H:i:s'
            ),$options );
        }

        public function calculate(){
            $opts=$this->options;
            $timezone=new DateTimeZone( $opts->timezone );
            $dob=new DateTime( date( $opts->format, strtotime( $this->dob ) ), $timezone );
            $now=new DateTime( date( $opts->format, strtotime( 'now' ) ), $timezone );
            $age = $now->diff( $dob );

            $result=(object)array(
                'years'     =>  $age->format('%y'),
                'months'    =>  $age->format('%m'),
                'days'      =>  $age->format('%d'),
                'hours'     =>  $age->format('%h'),
                'mins'      =>  $age->format('%i'),
                'secs'      =>  $age->format('%s')
            );
            $dob=$now=$age=null;
            return $result;
        }
    }

    $ua=new userage('1970-09-05');
    $age=$ua->calculate();

    echo '<pre>',print_r($age,true),'</pre>';

/*
    outputs
    -------
    stdClass Object
    (
        [years] => 45
        [months] => 2
        [days] => 26
        [hours] => 8
        [mins] => 53
        [secs] => 30
    )

*/