Date subtraction

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • un1xg33k@gmail.com

    #1

    Date subtraction

    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

    #2
    Re: Date subtraction

    un1xg33k wrote:
    Is there a php function to determine the difference between dates.
    Yes: it's pronounced "minus" and written "-".
    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_second s = $now - $birthdate;
    $diff_in_days = $diff_in_second s / (24*60*60);
    $diff_in_years = $diff_in_days / 365.25;

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

    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!

    Comment

    • un1xg33k@gmail.com

      #3
      Re: Date subtraction

      TY

      Comment

      • un1xg33k@gmail.com

        #4
        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?


        Comment

        • un1xg33k@gmail.com

          #5
          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?

          Comment

          • un1xg33k@gmail.com

            #6
            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?


            Comment

            Working...