Page 1 of 1

Get "Age" of person - script won't work

Posted: Thu Aug 18, 2011 9:07 am
by simonmlewis

Code: Select all

$dob = "$day.$month.$year";

$bday = new DateTime('$dob');
echo "$bday";
$date = (date('Y-m-d'));
$today = new DateTime($date);
$diff = $today->diff($bday);
printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
If I echo $dob, I get the date of birthday showing on screen.
If I echo $bday, it shows nothing.

And I get this error which means nothing to me:

[text]Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string ($dob) at position 0 ($): Unexpected character' in C:\xampp\phpMyAdmin\sell\includes\signup.inc:12 Stack trace: #0 C:\xampp\phpMyAdmin\sell\includes\signup.inc(12): DateTime->__construct('$dob') #1 C:\xampp\phpMyAdmin\sell\index.php(123): include('C:\xampp\phpMyA...') #2 C:\xampp\phpMyAdmin\sell\index.php(413): getPage() #3 {main} thrown in C:\xampp\phpMyAdmin\sell\includes\signup.inc on line 12[/text]

This works fine:

Code: Select all

<?php
$bday = new DateTime('01.01.2000');
$date = (date('Y-m-d'));
$today = new DateTime($date);

$diff = $today->diff($bday);

printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
?>
And produces the right results.

What am I doing wrong?

Re: Get "Age" of person - script won't work

Posted: Thu Aug 18, 2011 9:35 am
by simonmlewis
I've tried this

function calculateage($BirthDate)
{
list($Year, $Month, $Day) = explode("/", $BirthDate);

$YearDiff = date("Y") - $Year;

if(date("m") < $Month || (date("m") == $Month && date("d") < $DayDiff))
{
$YearDiff--;
}
return $YearDiff;
}

echo calculateage("2000/07/09");

But it produces 11, not 10.

Re: Get "Age" of person - script won't work

Posted: Thu Aug 18, 2011 10:27 am
by genix2011
The error is here:

Code: Select all

$bday = new DateTime('$dob');
it has to be

Code: Select all

$bday = new DateTime($dob);
You can only use variables inside Strings with "" not with ''

Greets.

Re: Get "Age" of person - script won't work

Posted: Thu Aug 18, 2011 2:03 pm
by Dorin85
Very nice catch genix2011. I was not aware of the "" vs '' issue.

Re: Get "Age" of person - script won't work

Posted: Thu Aug 18, 2011 2:24 pm
by Jonah Bron
The manual on strings, for future reference:

http://php.net/string