Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active November 11, 2015 20:34
Show Gist options
  • Save kjbrum/57cfedff813ed8304c07 to your computer and use it in GitHub Desktop.
Save kjbrum/57cfedff813ed8304c07 to your computer and use it in GitHub Desktop.
Prettify a range of dates.
<?php
/**
* Prettify a range of dates.
*
* @param mixed $start The start date
* @param mixed $end The end date
* @param string $format A date() string for formatting if the dates match
* @param string $format_day A date() string for formatting if they are different days
* @param string $format_month A date() string for formatting if they are different months
* @param string $format_year A date() string for formatting if they are different years
* @param string $divider The divider for parsing the formats
* @return string A prettified date() string for the date range
*/
function get_pretty_date_range( $start=null, $end=null, $format='F j, Y', $format_day='F j -- j, Y', $format_month='F j -- F j, Y', $format_year='M j, Y', $divider='--' ) {
$diff_month = false;
$diff_year = false;
// Make sure a start and end date are supplied
if( empty( $start ) || empty( $end ) ) {
return 'You need to supply a start and end date.';
}
if( ! is_valid_timestamp( $start ) ) {
$start = strtotime( $start );
}
if( ! is_valid_timestamp( $end ) ) {
$end = strtotime( $end );
}
// Check if the dates match
if ( date( 'Ymd', $start ) == date( 'Ymd', $end ) ) {
return date( $format, $start );
} else {
// Check if months differ
if( date( 'm', $start ) != date( 'm', $end ) ) {
$diff_month = true;
}
// Check if years differ
if( date( 'Y', $start ) != date( 'Y', $end ) ) {
$diff_year = true;
}
}
// Different years
if( $diff_year ) {
return date( $format_year, $start ).' - '.date( $format_year, $end );
}
// Different months
if( $diff_month ) {
$month = explode( $divider, $format_month );
return date( trim( $month[0] ), $start ).' - '.date( trim( $month[1] ), $end );
}
// Different days
$day = explode( $divider, $format_day );
return date( trim( $day[0] ), $start ).' - '.date( trim( $day[1] ), $end );
}
function is_valid_timestamp( $strTimestamp ) {
return ( (string)(int)$strTimestamp == $strTimestamp )
&& ( $strTimestamp <= PHP_INT_MAX )
&& ( $strTimestamp >= ~PHP_INT_MAX );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment