Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[WordPress] Find The Difference in Dates Using PHP (and WordPress)
* Determines the number of years that exist between the specified
* event custom post type and today's date.
* @access private
* @param WP_Post $event A custom post type representing an event.
* @return string $years The difference in years.
private function get_difference_in_dates( $event ) {
// If the post_date is empty, why are we here?
if ( empty( $event['post_date'] ) {
// Get the date for the start of the event and te
$start = date( 'n/j/Y', strtotime( $event['post_date'] ) );
$today = date( 'n/j/Y' );
// Get the date for the start of the event and today's date.
$start = new \DateTime( $start );
$end = new \DateTime( $today );
// Now find the difference in years.
$difference = $start->diff( $end );
$years = $difference->y;
// If the difference is less than one, we'll return a string of "< 1".
$years = ( 1 > $years ) ?
'< 1' :
return $years;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.