SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jan 2008
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Rounding up problem

    Hello,

    I've used this code to convert a date of birth entered by a user into an age -

    Code PHP:
    <?php
    $dob = '1971-06-21';
    $age = (strtotime(date("Y-m-d")) - strtotime($dob)) / 31536000;
    echo $age;
    ?>

    Of course this returns a number with many decimal places - 38.027397260274. So I cast $age as an integer as I want to display the user's age on the site -

    Code PHP:
    <?php
    $dob = '1971-06-21';
    $age = (strtotime(date("Y-m-d")) - strtotime($dob)) / 31536000;
    echo (int)$age;
    ?>

    But now the code returns 38 even if $dob is set to tomorrow's date, so the person would still be 37. In fact it does this right up until '1971-07-02', when it finally starts returning 37.

    Hope I've explained myself clearly enough... can someone tell me a better way of dealing with this?

    Thanks.

  2. #2
    SitePoint Member
    Join Date
    Jan 2008
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Never mind, have sorted it out.

  3. #3
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You can't use UNIX timestamps (which strtotime returns) for dates of birth. Time 0 is 1970, and people were born before 1970.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •