I have a custom field "DOB" on my custom post type which is in [Ymd] format. I want to compare that date of birth to current time and want to show "You are # years # months."

I am able to calculate Years only but it is not accurate. Help me.

1 Answer 1


You create two date objects and compare with the diff() methode.

$from = new DateTime( '1970-01-01' );
$to = new DateTime('today');
$years = $from->diff($to)->y;
$months =  $from->diff($to)->m;

echo $years . ' years and ' . $months . ' months.';

=> 46 years and 1 months.

  • Thanks Soren but What if we want to display 46 years and 213 days ? in that format ?
    – Nis
    Commented Feb 15, 2016 at 4:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.