If else statement based on date_diff value

I have a problem with dates.

I need to add if-else logic to show different content.

It’s based on date_diff values.
And here’s go a problem:

I need to show button if today’s date – post_modified date >= 3 hours
And if it’s less than 3 hour difference – show default message: “Wait for x minutes before using button”.

Here goes my efforts:

<?php
  $now = new DateTime();
  $currentDateTime = $now->getTimestamp();
  $postUpdated = $post->post_modified;
  if ($currentDateTime - $postUpdated >= 1) :
?>
<button>Some value</button>
<?php  else:  ?>
 <p>Wait, please</p>
<?php endif; ?>

Hope u can help me. Thank you.

1 Answer
1

You can use strtotime() to convert the time to an integer, and then do a conditional.

// Get the current time
$now = strtotime("now");
// Convert post's modification time to int
$postUpdated = strtotime( $post->post_modified );
// Check if 3 hours has passed, each hour is 60*60 seconds
if ( $now - $postUpdated >= 3*60*60 ) {
    // First conditional
} else {
    // Second conditional
}

Also, if the time’s format is known ( which is usually 0000-00-00 00:00:00 ), you can directly use strftime(). Here is a quick example:

$timestamp = strftime("%Y-%m-%d %h:%M:%S %a", time() - 3*60*60);

Now you have a formatted value of 3 hours before, which you can use in date_diff().

Leave a Comment