Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active May 16, 2017 01:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/d72e8d0e5d66d5e905f771254c3ad566 to your computer and use it in GitHub Desktop.
Save tommcfarlin/d72e8d0e5d66d5e905f771254c3ad566 to your computer and use it in GitHub Desktop.
[WordPress] Find The Difference in Dates Using PHP (and WordPress)
<?php
/**
* 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'] ) {
return;
}
// 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' :
(string)$years;
return $years;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment