Last active
June 25, 2019 05:06
-
-
Save jb510/23dc81a2228296322811 to your computer and use it in GitHub Desktop.
Pretty PHP Date Ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Verbose Beautified Date Range | |
* | |
* @access public | |
* @param mixed $start_date | |
* @param mixed $end_date | |
* @return $date_range (beautified date range) | |
* @license WTFPL | |
* | |
* @author Jon Brown <[email protected]> | |
* @since 1.0 | |
*/ | |
function jb_verbose_date_range($start_date = '',$end_date = '') { | |
$date_range = ''; | |
// If only one date, or dates are the same set to FULL verbose date | |
if ( empty($start_date) || empty($end_date) || ( date('FjY',$start_date) == date('FjY',$end_date) ) ) { // FjY == accounts for same day, different time | |
$start_date_pretty = date( 'F jS, Y', $start_date ); | |
$end_date_pretty = date( 'F jS, Y', $end_date ); | |
} else { | |
// Setup basic dates | |
$start_date_pretty = date( 'F j', $start_date ); | |
$end_date_pretty = date( 'jS, Y', $end_date ); | |
// If years differ add suffix and year to start_date | |
if ( date('Y',$start_date) != date('Y',$end_date) ) { | |
$start_date_pretty .= date( 'S, Y', $start_date ); | |
} | |
// If months differ add suffix and year to end_date | |
if ( date('F',$start_date) != date('F',$end_date) ) { | |
$end_date_pretty = date( 'F ', $end_date) . $end_date_pretty; | |
} | |
} | |
// build date_range return string | |
if( ! empty( $start_date ) ) { | |
$date_range .= $start_date_pretty; | |
} | |
// check if there is an end date and append if not identical | |
if( ! empty( $end_date ) ) { | |
if( $end_date_pretty != $start_date_pretty ) { | |
$date_range .= ' - ' . $end_date_pretty; | |
} | |
} | |
return $date_range; | |
} | |
/* To actually make use of this in WordPress you'd feed it something like this where the dates are stored as unix time stamps | |
$start_date = get_post_meta( get_the_ID(), 'jb_start_timestamp', true ); | |
$end_date = get_post_meta( get_the_ID(), 'jb_end_timestamp', true ); | |
if ( (!empty($start_date)) || (!empty($end_date)) ) { | |
echo '<span class="pretty-date-range"---->'; | |
echo jb_verbose_date_range( $start_date , $end_date ); | |
echo '<!-- pretty-date-range -->'; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment