Connecting Tech Pros Worldwide Help | Site Map

Date subtraction

un1xg33k@gmail.com
Guest
 
Posts: n/a
#1: Apr 11 '07
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

Toby A Inkster
Guest
 
Posts: n/a
#2: Apr 11 '07

re: Date subtraction


un1xg33k wrote:
Quote:
Is there a php function to determine the difference between dates.
Yes: it's pronounced "minus" and written "-".
Quote:
I'd like to take a birthdate and then determine how old a person is
dynamically and simply return the age in years.
<?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!
un1xg33k@gmail.com
Guest
 
Posts: n/a
#3: Apr 11 '07

re: Date subtraction


TY

un1xg33k@gmail.com
Guest
 
Posts: n/a
#4: Apr 11 '07

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?


un1xg33k@gmail.com
Guest
 
Posts: n/a
#5: Apr 11 '07

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?

un1xg33k@gmail.com
Guest
 
Posts: n/a
#6: Apr 11 '07

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?


Closed Thread