How to calculate elapsed years from the current time in WordPress

- by

I’ve implemented a neat feature on the front page of my other website: it calculates how long Julia and I have been married. Rather than this being one of those items I will certainly forget to update in the future, it uses a shortcode in the regular page text to calculate this value.

The WordPress function current_time() returns the value of “right now”, and the rest is PHP maths under the hood. Here’s how I did it:

<?php
function guru_yearsmarried() {
// dates to be calculated
$dateMarried = strtotime( '2004-04-22 15:00:00' );
$currentDate = strtotime( current_time ( 'mysql' ));
// calculate the time in seconds and convert
$seconds = $currentDate$dateMarried;
$years = $seconds / 60 / 60 / 24 / 365.242199;
return round ($years);
}
// register shortcode
function guru_shortcodes() {
add_shortcode( 'yearsmarried', 'guru_yearsmarried' );
}
add_action( 'init', 'guru_shortcodes' );
view raw yearsmarried.php hosted with ❤ by GitHub

I’m specifying both times as string values. The first one is my known wedding date (Vegas time), and the second is returned by WordPress. The mysql parameter returns the date in the same format I’m supplying above it. The PHP function strtotime will then convert these values into a date object so they can be calculated via subtraction.

The result of that gives us seconds, which I’m converting via minutes, hours and days into years. It’s such a crummy value because of our leap year calculation in the Gregorian calendar. My year value will be a float, so I’m rounding it down to get a whole number.

The last block sets up my code as a shortcode. I’ve explained how to do this in detail in a previous article.

Further Reading

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.