0

What's the best way to show a time stamp based on different times? For example: if a post is under 24 hours, show %% mins/hours ago. If a post is over 24 hours, show month/day/time. If a post if over a year ago, show month/day/year/time.

I've done this so far:

<?php if(get_the_time('G') < 23) {
the_time('Y'); } else {
the_time('F j, Y at g:i a'); } ?>
1

Check out human_time_diff():

if ( DAY_IN_SECONDS < ( $time = current_time( 'timestamp' ) ) - ( $time_post = get_the_time( 'U' ) ) )
    echo human_time_diff( $time_post, $time ) . ' ago';
else
    the_time( 'F j, Y at g:i a' );

DAY_IN_SECONDS is a handy "helper" constant in WordPress, along with:

  • MINUTE_IN_SECONDS
  • HOUR_IN_SECONDS
  • WEEK_IN_SECONDS
  • YEAR_IN_SECONDS
0

Further, if you want to work with the amount of days, hours etc. you can use DateTime and DateInterval objects:

global $post;

$utc       = new DateTimeZone( 'UTC' );
$post_date = new DateTime( $post->post_date_gmt, $utc );
$now       = new DateTime( 'now', $utc );
$diff      = $post_date->diff( $now );

$diff is now an instance of the DateInterval Object with the following properties:

object(DateInterval)#4 (8) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(2)
  ["d"]=>
  int(16)
  ["h"]=>
  int(19)
  ["i"]=>
  int(29)
  ["s"]=>
  int(59)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(75)
}
0

Thanks for the responses! This is the solution:

<?php
if ( DAY_IN_SECONDS < ( $time = current_time( 'timestamp' ) ) - ( $time_post = get_the_time( 'U' ) ) )
    echo human_time_diff( $time_post, $time ) . ' ago';
elseif ( WEEK_IN_SECONDS < ( $time - $time_post ) )
    the_time( 'D / g:i a' );
elseif ( YEAR_IN_SECONDS < ( $time - $time_post ) )
    the_time( 'F j / g:i a' );
else
    the_time( 'F j, Y / g:i a' ); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.