-1

I am trying to use this age calculator to calculate users' ages, which is stored in a MySQL database. I thought this would work, but it doesn't seem to.

My problem is that I don't know how to get the date, from a users table from 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;
?>
Community
  • 1
  • 1
Albert MN.
  • 713
  • 1
  • 16
  • 33

1 Answers1

1

I just wrote this simple class that uses the DateTime class and associated methods - should be easy enough to adapt your date string to be in the correct format.

    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
    )

*/
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • That doesn't solve my problem. The script itself works perfectly fine, my only problem is taking the date from a MySQL users table. – Albert MN. Dec 01 '15 at 09:22
  • I see that 3 mins ago you added that the problem itself was merely getting the data from the db. That should be a fairly straightforward sql query – Professor Abronsius Dec 01 '15 at 09:25