Skip to content
Advertisement

If less than 1 month convert timestamp to time ago in PHP

I’m sure there are many similar questions but I already tried many of them it seems impossible to get the results I want. So what I want is to convert the timestamp on my WordPress posts to show “1 minute ago, 1 day ago, 1 week ago etc.” but only if the date is equal or less than 1 month, otherwise to display the normal date.

EDIT: So far it shows only like this

enter image description here

And this is what I want:

enter image description here

$posted = get_the_time('U');

if( (int)get_the_time( 'm' ) <= 1 ) {
    echo human_time_diff($posted, current_time( 'U' )). " ago";
} else {
    the_time('j F Y');
}
        

Advertisement

Answer

You can then check if the timestamp assigned to $posted is greater i.e. more recent than the timestamp of a month ago.

if it is more recent, then convert it to a human time ago and append the word ago if its not more recent then use the date('d F Y) or whatever format you want long dates to appear in to convert the timestamp back to a readable date.

<?php
    $posted = get_post_time();
    $date = $posted >= strtotime('-1 month') ? human_time_diff($posted) . ' ago' : date('d F Y', $posted);
?>

<?php echo $date; ?>

Returns the expected date format of time ago for dates less than 1 month ago, and the full date for dates longer than 1 month ago…

See image for example. wordpress example

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement