I want to calculate the difference between post's publishing time and current time, and I want to read that value as a number (number of hours, minutes, seconds whatever, i just want it to be a number).

The reason is I want to do something depending on the post's age.

Would this code work?

$date = get_post_time('G', true, $post);
$current_time = current_time( 'mysql', $gmt = 0 );
$newer_date = strtotime( $current_time );

$postsage = $newer_date - $date;

if($postsage < 7200){
// if post is between one and two hours old
else if (($postsage >= 7200) && ($postsage <=14400)){ 
else {

Is this code bit valid?

1 Answer 1


To print relative time on posts automatically we can use get_the_date filter. We will check the time difference and print it in human readable form.

// Relative date & time
function wp_relative_date() {
  return human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago';
add_filter( 'get_the_date', 'wp_relative_date' ); // for posts
add_filter( 'get_comment_date', 'wp_relative_date' ); // for comments

And in your theme use <?php echo get_the_date(); ?> to print relative time.

If you do not need relative time for comments then remove following from code.

add_filter( 'get_comment_date', 'wp_relative_date' ); // for comments


To get time difference in seconds. Use this.

$seconds = current_time( 'timestamp' ) - get_the_time('U');

Now you can use $seconds in your if conditions.

  • I don't want to print the time difference, i want to know what it is, check it in my code, and depending on the value, do something. If the difference between publishing date and current time is, for example, 6 hours or 10800 seconds, I want to know a way to calculate that, so I can 'ask' in my code if(time < 10800){do something} else {do something else 2 }
    – idjuradj
    Oct 2, 2014 at 18:31
  • You can use $seconds = current_time( 'timestamp' ) - get_the_time('U'); to get time difference in seconds. Check edit
    – Robert hue
    Oct 2, 2014 at 19:03
  • Yep, the $seconds = current_time( 'timestamp' ) - get_the_time('U'); does the job. Thanks for the help ;)
    – idjuradj
    Oct 2, 2014 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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