squidg squidg - 1 year ago 103
PHP Question

PHP Rendering Age

I'm using WordPress and I want age to update dynamically in all my posts.

I am using the below code in my functions.php:

function internoetics_determine_age($atts) {
extract( shortcode_atts( array(
'dob' => '' /* See post for date formats */
), $atts ) );
$age = floor((time() - strtotime($dob)) / 31556926);
return $age;
add_shortcode('age', 'internoetics_determine_age');

I then use the shortcode [age dob="1945"] but the result that is displayed is -16, it should be 71.

Any ideas?

Answer Source

strtotime function works with dates so strtotime(1945) is incorrect. strtotime('1945-01-01') is correct so:

$age = floor((time() - strtotime(((int)$dob) . '-01-01')) / 31556926);

But you should just use:

$age = date('Y') - ((int)$dob);

*((int)$dob) just in case $dob has different format

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download