Skip to content

Instantly share code, notes, and snippets.

@eriku
Last active August 29, 2015 14:18
Show Gist options
  • Save eriku/b2640af589d1c289d4df to your computer and use it in GitHub Desktop.
Save eriku/b2640af589d1c289d4df to your computer and use it in GitHub Desktop.
Output date range between 2 dates.
<?php
function isValidTimestamp($timestamp) {
return ((string) (int) $timestamp === $timestamp)
&& ($timestamp <= PHP_INT_MAX)
&& ($timestamp >= ~PHP_INT_MAX);
}
function get_date_range($startDate, $endDate) {
$output = '';
$diff = false;
if ( !isValidTimestamp($startDate) ) {
$startDate = strtotime($startDate);
}
if (!isValidTimestamp($endDate) ) {
$endDate = strtotime($endDate);
}
if ( $startDate !== $endDate ) {
$diff = true;
if ( date('Y', $startDate) !== date('Y', $endDate) ) {
$startDateFormat = date('F j, Y', $startDate);
$endDateFormat = date('F j, Y', $endDate);
}
elseif ( date('F', $startDate) !== date('F', $endDate) ) {
$startDateFormat = date('F j', $startDate);
$endDateFormat = date('F j, Y', $endDate);
}
else {
$startDateFormat = date('F j', $startDate);
$endDateFormat = date('j, Y', $endDate);
}
} else {
$startDateFormat = date('F j, Y', $startDate);
}
$output .= '<span class="date-start">' . $startDateFormat . '</span>';
if ( $diff ) {
$output .= '<span class="date-separator"> - </span>';
$output .= '<span class="date-end">' . $endDateFormat . '</span>';
}
return $output;
}
function date_range($startDate, $endDate) {
echo get_date_range($startDate, $endDate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment