• suge1w

    (@suge1w)


    I’ve struggling to find a solution to this.

    I have three taxonomies: ‘dob’, ‘mob’, ‘yob’ and I’m trying to calculate the age in years using all 3.

    The code I’ve been messing with:

    function age_in_years() {
    global $post;
    $year_of_birth = get_post_meta( get_the_ID( $post->ID ), 'yob', true );
    $date1 = strval( $year_of_birth );
    $date2 = strval( date( 'Y') );
    $age = $date2 - $date1;
    return $age;
    }

    Could anyone lend a hand?

Viewing 8 replies - 1 through 8 (of 8 total)
  • Moderator bcworkz

    (@bcworkz)

    Concatenate the values into a normal English date string. Use slashes for American format mm/dd/yyyy and hyphen for European dd-mm-yyyy.
    $age = (time()-strtotime( $date_string ))/31557600;
    31557600 is the number of seconds in a year.

    Thread Starter suge1w

    (@suge1w)

    Thanks for that response.

    How exactly would I concatenate the values?

    catacaustic

    (@catacaustic)

    What you’d need is something like this…

    `$year = get_post_meta( $post->ID, ‘yob’, true );
    $month = get_post_meta( $post->ID, ‘mob’, true );
    $day = get_post_meta( $post->ID, ‘dob’, true );

    $dob = date( ‘Y-m-d’, strtotime( $year.’-‘.$month.’-‘.$day ));

    $age = date_diff( date_create( $dob ), date_create( ‘today’ ))->y;’

    Thread Starter suge1w

    (@suge1w)

    That code just seems to return the same value – 46.
    Echo’ing $dob returns 1970-01-01.

    catacaustic

    (@catacaustic)

    So what are the values for $yob, $mob and $dob? And is the real answer 46 years old?

    Thread Starter suge1w

    (@suge1w)

    The format I’m laying my dates out in is DD-MM-YYYY. For example, 18/08/1994 should = 21

    catacaustic

    (@catacaustic)

    That is the wrong format for the calculation functions. That’s why I did it the way that I did. It needs to be in that order so that the computer knows what date is supposed to be where. Anything else can be very ambiguous.

    Moderator bcworkz

    (@bcworkz)

    Ambiguous indeed. If you really want to use DD-MM-YYYY format, do NOT use slashes, use hyphens. ’18-08-1994′ Then strtotime() will make the correct assumption that you intend days first. When you use slashes, it will assume you intend months first (American format). By using the 4 digit year first, as catacaustic points out, there is no ambiguity and no assumption is needed. As coders, that is what we all should aspire to ??

    Not that it matters for human ages, but 31557600 sec/year fails to account for the lack of a leap year every 400 years. A better constant for long term calculations is 31556926. There’s actually fractional seconds in the correct value, but that is too pedantic even for me!

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Calculate age from 3 terms’ is closed to new replies.