Skip to content

Instantly share code, notes, and snippets.

@amiut
Last active September 19, 2020 02:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save amiut/c2cec40120931487af035d190ea867cc to your computer and use it in GitHub Desktop.
Save amiut/c2cec40120931487af035d190ea867cc to your computer and use it in GitHub Desktop.
/**
* Time ago - Human time diff enhanced
*
* @param string $timeformat Fallback date format
* @param int $timestamp Post or comment or anyhing's timestamp
* @return string
*/
if( ! function_exists('dw_time_ago') ){
function dw_time_ago( $timeformat = 'j F Y H:i', $timestamp = '' ){
if( ! $timestamp ){
global $post;
$timestamp = get_the_time( 'U', $post->ID );
if( ! $timestamp ) return;
}
$diff = current_time('timestamp') - $timestamp;
$is_today = date( 'Y-m-d', current_time('timestamp') ) == date( 'Y-m-d', $timestamp );
$is_yesterday = date( 'Y-m-d', current_time('timestamp') - 86400 ) == date( 'Y-m-d', $timestamp );
if( $diff < 0 ) return;
// less than 2 minutes - print just now or moments ago
if( $diff < 120 ){
$text = __('Just now', 'textdomain');
}
// less than one hour - print x minutes ago
elseif( $diff < 3600 ){
$text = sprintf( __('%d minutes ago', 'textdomain'), ( floor( $diff / 60 ) % 60 ) );
}
// less than 7 hours - print x hours ago
elseif( $diff < 25200 ) {
$text = sprintf( __('%d hours ago', 'textdomain'), ( floor( $diff / 60 / 60 ) % 24 ) );
}
// belongs to today - print Today xx:xx
elseif( $is_today ){
$text = sprintf( __('Today %s', 'textdomain'), date_i18n( 'H:i', $timestamp ) );
}
// belongs to yesterday - print Yesterdat xx:xx
elseif( $is_yesterday ){
$text = sprintf( __('Yesterday %s', 'textdomain'), date_i18n( 'H:i', $timestamp ) )
} else{
$text = date_i18n( $timeformat, $timestamp );
}
return $text;
}
}
@amiut
Copy link
Author

amiut commented Feb 8, 2018

This is a simple enhanced version of Wordpress human_time_diff function to show more friendly dates in Wordpress.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment