Relative time – how to calculate difference beween post publish date and current time

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?

Solutions Collecting From Web of "Relative time – how to calculate difference beween post publish date and current time"

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

EDIT

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.