Jeff Davidson
Jeff Davidson

Reputation: 1929

Comparing dates to in if statement

My intended goal is to have it see if the post allows comments and if it does then check to make sure the date_comments_expires is NOT before the passed day. I'm not quite sure how to finish this if statement. Any help?

if ($mainNews[0]['allow_comments'] == 'Yes' AND $mainNews[0]['date_comments_expire'] == ) {

EDIT:

Here's my updated code in which I'm getting a call to member function getTimeStamp of non object

if ($mainNews[0]['allow_comments'] == 'Yes' AND $mainNews[0]['date_comments_expire']->getTimestamp() > time() ) {
                    echo "<a href=\"#\"></a><span>".$mainNews[0]['number_of_comments']."</span>";   
                }    

Upvotes: 0

Views: 106

Answers (1)

anon
anon

Reputation:

This depends entirely on what is contained within the date_comments_expire index of your array. I would expect it to either be a unix timestamp stating when the comments expire, or a reasonable textual interpretation thereof.

If you're using a unix timestamp, then you're doing great. If it's text, then you're going to need to convert it into a unix timestamp before continuing. The best function for this is strtotime(). It can parse a variety of textual datetime representations, and will return a unix timestamp as a result.

Once you have the endpoint represented as a timestamp, you can compare it against the current time. For this, you can use the time() function, which returns the current time as a unix timestamps.

Since unix timestamps are just integers (specifically, the number of seconds since Jan. 1, 1970), this is a simple comparison.

In the end, your code would look like this:

// convert to timestamp if necessary, remove if unneeded
$commentExpiry == strtotime($mainNews[0]['date_comments_expire']);

if ($mainNews[0]['allow_comments'] == 'Yes' AND 
    $commentExpiry > time()) {
  //submit comments
} else {
  //error handling
}

Upvotes: 2

Related Questions