Jacob
Jacob

Reputation: 900

PHP - Comparing Database DateTime with Current DateTime

I've seen a few different DateTime comparisons on StackOverflow, but I can't seem to get it right. I need to be able to retrieve a row from the database, compare the DateTime with the current DateTime, and then evaluate whether or not it.

In this case, I need to check if the current row has expired or not.

if (strtotime(new DateTime()) > strtotime($row['expiration_date'])) {
  $response = 'Valid Coupon!';
} else {
  $response = 'Coupon Expired';
}

I've tried a few different ways, but none seem to work properly.

"2017-07-15 13:42:31 > 2017-07-15 14:27:31"
// and 
"2017-07-15 13:42:31 > 2017-07-14 13:03:04"

Both return as a Valid Coupon.

I've tried a number of things, but can't seem to figure out why these dates aren't working properly. Any thoughts?

Upvotes: 3

Views: 3658

Answers (2)

Farhan Ghaffar
Farhan Ghaffar

Reputation: 73

You should change your new DateTime() and expatriation date and time into Unix timestamp. When you convert your date into Unix timestamp, it will show in a number format. This way, you will compare your value.

For example:

$current_date = strtotime(new DateTime); //your current date and time 
$expatriation_date = strtotime($row['expiration_date']);  //your database data and time values // 
if($current_date > expatriation_date ){
    $response = 'Valid Coupon!';              
}
else{
    $response = 'Coupon Expired';
}

Your current date and time in Unix timestamp is "1500118951" and expatriation date and time in Unix timestamp is "1500121651". You can compare your value easily.

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

Use ->format

 if (strtotime((new DateTime())->format("Y-m-d H:i:s")) > strtotime($row['expiration_date'])) {
   $response = 'Valid Coupon!';
 } else {
    $response = 'Coupon Expired';
 }

Check this live : https://eval.in/833030

Or you can use

   (new DateTime())->getTimestamp();

Instead of

   strtotime((new DateTime())->format("Y-m-d H:i:s"));

Check this : https://eval.in/833038

Upvotes: 10

Related Questions