Last active
November 11, 2015 20:34
-
-
Save kjbrum/622f01e71cbd25c76535 to your computer and use it in GitHub Desktop.
Prettify a range of times.
This file contains hidden or 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 | |
/** | |
* Prettify a range of times. | |
* | |
* @param mixed $start The start date, with time | |
* @param mixed $end The end date, with time | |
* @return string A prettified date() string for the time range | |
*/ | |
function get_pretty_time_range( $start='', $end='' ) { | |
$diff_meridiem = false; | |
$remove_minutes = false; | |
// Make sure a start and end date are supplied | |
if( empty( $start ) || empty( $end ) ) { | |
return 'You need to supply a start and end time.'; | |
} | |
if( ! is_valid_timestamp( $start ) ) { | |
$start = strtotime( $start ); | |
} | |
if( ! is_valid_timestamp( $end ) ) { | |
$end = strtotime( $end ); | |
} | |
// Check if minutes need to exist | |
if( date( 'i', $start ) == 0 && date( 'i', $end ) == 0 ) { | |
$remove_minutes = true; | |
} | |
// Check if the times match | |
if ( date( 'H:i:s', $start ) == date( 'H:i:s', $end ) ) { | |
if( $remove_minutes ) { | |
return date( 'g A', $start ); | |
} else { | |
return date( 'g:i A', $start ); | |
} | |
} else { | |
// Check if meridiems differ | |
if( date( 'A', $start ) != date( 'A', $end ) ) { | |
$diff_meridiem = true; | |
} | |
} | |
// Different meridiems | |
if( $diff_meridiem ) { | |
if( $remove_minutes ) { | |
return date( 'g A', $start ).' - '.date( 'g A', $end ); | |
} else { | |
return date( 'g:i A', $start ).' - '.date( 'g:i A', $end ); | |
} | |
} | |
// Format for having different hours or minutes | |
if( $remove_minutes ) { | |
return date( 'g', $start ).' - '.date( 'g A', $end ); | |
} else { | |
return date( 'g:i', $start ).' - '.date( 'g:i A', $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