# Date subtraction

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Is there a php function to determine the difference between dates.

I'd like to take a birthdate and then determine how old a person is
dynamically and simply return the age in years.

TIA

## Re: Date subtraction

un1xg33k wrote:

Yes: it's pronounced "minus" and written "-".

<?php
\$birthdate = strtotime('1 June 1980');
\$now       = time();

\$diff_in_seconds = \$now - \$birthdate;
\$diff_in_days    = \$diff_in_seconds / (24*60*60);
\$diff_in_years   = \$diff_in_days    / 365.25;

printf("I am %d years old!", (int)\$diff_in_years);
?>

The above may misbehave on the day before/after/of someone's birthday due
to stupid bloody leap years, which are always annoying, but it should give
you a basic idea of how date calculations can be done.

If you're very concerned about them, it's not rocket science to counteract
the effect of leap years.

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!

## Re: Date subtraction

OK, a bit more help.

As you can tell I'm on php expert and am hacking a page to add this
into it.

The birthday is stored in mysql as a date and shows up as 2000-11-02.

Do I need to do anything to be able to subtract that date from the
current date?

Also, how can I get a variable to show just the integer portion,
rather than doing it through a printf?

## Re: Date subtraction

Ok, so the strtotime will take the date in that format and appears to
work. Now I just need the way to assign the integer to the variable.

Also what's the easiest way to put in something like <1 if the age is
less than one?

## Re: Date subtraction

Got it working:

\$now       = time();
\$birthday = strtotime(\$row[birthday]);
\$age    = (integer)((\$now - \$birthday) / 31557600);
if (\$age=="0")
{
\$age = "<1";
}

Any better way to do this?