Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two dates in PHP and MYSQL

Tags:

date

php

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.

like image 732
Ketan Lathiya Avatar asked Apr 23 '26 17:04

Ketan Lathiya


2 Answers

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 !!!!

like image 141
Kausha Thakkar Avatar answered Apr 25 '26 08:04

Kausha Thakkar


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.
like image 27
Ruslan Osmanov Avatar answered Apr 25 '26 07:04

Ruslan Osmanov