I need a php age calculating script for multiple D.O.B.'s on a single page

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fabio Passaro
    New Member
    • Sep 2010
    • 1

    #1

    I need a php age calculating script for multiple D.O.B.'s on a single page

    Hi

    I need an age calculating script that will list the age of an animal when D.O.B. has been provided and for it to work multiple instances on the same page.

    I list details of 6 or more animals per page and need a script that will display the age of each the animals as just days, months and days, or years, months and days dependant on the a D.O.B. provided either on show or hidden within the page.


    I have scoured the net looking for such scripts and have found one that displays a single calculation for the page but I need multiples. I have used Java scripts and other php scripts but they seem to fail sometimes reporting an animal under one month old as 9 months old??

    Cheers
  • kovik
    Recognized Expert Top Contributor
    • Jun 2007
    • 1044

    #2
    Use strtotime() to build the timestamp of their birth date and the timestamp of the current date. Subtract the birth date from the current date to get the overall time. This value is the number of seconds between then and now.

    This is where it gets tricky. This value is the amount of seconds that has passed between your dates, but offset by 1970 years (Unix Epoch), at least according to the timestamp data format. You can get a fairly accurate value with the date() function. It will likely be off by several days.

    Code:
    $birthday = strtotime('1987-03-27');
    $today = time();
    $difference = ($today - $birthday);
    
    echo 'I am '
        . (date('Y', $difference) - 1970)
        . ' years, '
        . date('n', $difference)
        . ' months, and '
        . date('j', $difference)
        . ' days old';
    To be more accurate, you would need to start at today's timestamp and work backwards.
    1. Years: Use the date() function to determine if the year you are subtracting is a leap year (so you know to subtract 365 or 366 days) until the timestamp is less than the birth date. Then, backtrack by one year.
    2. Months: Do the same with months, using the date() function to determine id the month you are subtracting has 28, 29, 30, or 31 days (use the leap year value to determine February). Subtract until the timestamp is less than the birth date, then backtrack by one month.
    3. Days: Just subtract days from the timestamp until the time stamp is less than the birth date. Then, backtrack by one day. One day is 60*60*24 seconds long. Use that as the basis for all calculations.


    I'd do it myself.. but eh.

    Comment

    Working...