Skip to content

Instantly share code, notes, and snippets.

@Asikur22
Last active November 22, 2022 06:47
Show Gist options
  • Save Asikur22/399516be1a0aaee719bfa9b54ab0c441 to your computer and use it in GitHub Desktop.
Save Asikur22/399516be1a0aaee719bfa9b54ab0c441 to your computer and use it in GitHub Desktop.
PHP Relative Date
/*
* Relative Date.
*/
function relative_date( $date, $type = 'string' ) {
$today_timestamp = strtotime( date( 'M j, Y' ) );
$date_timestamp = strtotime( $date );
$diff = ( $date_timestamp - $today_timestamp ) / 86400;
$html = '';
$tense = $diff > 0 ? 'future' : 'past';
if ( $diff >= 0 && $diff < 1 ) {
$html = 'Today';
} elseif ( $diff >= 1 && $diff < 2 ) {
$html = 'Tomorrow';
} elseif ( $diff >= - 1 && $diff < 0 ) {
$html = 'Yesterday';
} elseif ( abs( $diff ) < 45 ) {
if ( $diff > 0 ) {
$diff = floor( $diff );
$html = 'In ' . $diff . ' day' . ( $diff != 1 ? 's' : '' );
} else {
$diff = abs( floor( $diff ) );
$html = $diff . ' day' . ( $diff != 1 ? 's' : '' ) . ' ago';
}
} else {
$html = date( 'l, j F, Y', $date_timestamp ? $date_timestamp : time() );
}
if ( $type == 'array' ) {
return [ 'string' => $html, 'tense' => $tense ];
} else {
return $html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment