Connecting Tech Pros Worldwide Help | Site Map

Date subtraction

  #1  
Old April 11th, 2007, 05:25 PM
un1xg33k@gmail.com
Guest
 
Posts: n/a
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

  #2  
Old April 11th, 2007, 06:25 PM
Toby A Inkster
Guest
 
Posts: n/a

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!
  #3  
Old April 11th, 2007, 06:45 PM
un1xg33k@gmail.com
Guest
 
Posts: n/a

re: Date subtraction


TY

  #4  
Old April 11th, 2007, 07:35 PM
un1xg33k@gmail.com
Guest
 
Posts: n/a

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?


  #5  
Old April 11th, 2007, 07:35 PM
un1xg33k@gmail.com
Guest
 
Posts: n/a

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?

  #6  
Old April 11th, 2007, 07:55 PM
un1xg33k@gmail.com
Guest
 
Posts: n/a

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


Similar Threads
Thread Thread Starter Forum Replies Last Post
how can i display date subtraction sumaiya answers 2 May 9th, 2007 07:38 AM
date subtraction calculations seshu answers 9 February 8th, 2007 02:31 PM
Date Subtraction rsutradhar_python answers 3 June 18th, 2006 05:35 PM
Date Subtraction/Formatting Issues David Doing answers 4 November 20th, 2005 07:24 AM