Ketan Lathiya
Ketan Lathiya

Reputation: 732

Comparing two dates in PHP and MYSQL

I want to compare two dates and time values in PHP. One date is coming from MySQL, and second one is the current date. I want to run some code when both dates are the same. I tried the code below, but condition satisfies any time which is wrong.

$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if($current_datetime == $send_date){
    //I want to run some code here
}else{
}

What is wrong with the code? I also tried to covert both dates with strtotime() before comparing, but it gave me the same issue. The above condition satisfies any time even if both dates are different.

Upvotes: 3

Views: 12398

Answers (3)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

One way is to fetch the Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) from MySQL, then operate on the numbers:

$row = get_db_row("SELECT UNIX_TIMESTAMP(send_date) AS send_date_ts
  FROM table WHERE $condition");
$hours = (int) ($row['send_date_ts'] / 3600);
$current_hours = (int) (time() / 3600);
if ($hours == $current_hours) {
  // current hour
}

Timestamps are convenient because:

  • there is no need to take the format into account;
  • operations on numbers are usually faster;
  • the code looks cleaner.

Upvotes: 2

S.I.
S.I.

Reputation: 3375

Try this. On my server is working just great I've got something else because they aren't equal. Date which I receive from database is type datetime format 2015-04-13 09:03:49

<?php
     $current_datetime = strtotime(date('Y-m-d H:i'));
     $send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
     if($current_datetime == $send_date){
         //I want to run some code here
         echo 'something';
     }else{ 
         echo 'something else';
     }

Output:

echo $current_datetime . '<br/>';
2016-10-17 09:19

echo $send_date .'<br/>';    
2015-04-13 09:03

// result
something else

Upvotes: -1

Kausha Thakkar
Kausha Thakkar

Reputation: 136

Try this :

$current_datetime = date('Y-m-d H:i');
$send_date = date("Y-m-d H:i", strtotime($row['send_date'])); // suppose $row['send_date']'s value is '2016-10-17 15:00'
if(strtotime($current_datetime) == strtotime($send_date)){
    //I want to run some code here
}else{
}

Hope it helps !!!!

Upvotes: 9

Related Questions