1

I want to compare two dates, the first is my current date and the second is a date from database.

When I see both of them they looks identical, but PHP gives me another result. I tried to compare using functions like strcmp. I simplified my code so you can understand it easier.

<?php
$users_day = "20".date("y-m-d");
$looper = 0 ;
$all_users_selection = mysql_query("SELECT * FROM user");
while($user_rows = mysql_fetch_array($all_users_selection) )
{
    if($user_rows['user_lastseen'] != NULL)
    {
        //Getting user lastseen day and hour
        $db_user_date[$looper] = substr(($user_rows['user_lastseen']) ,0 , 10);
        $db_user_curr[$looper] = $user_rows['username'];
        //Comparing day then hour
        if (strcmp($users_day,$db_user_date[$looper]) != 0)
        {
            //Set offline
            $current_user_update = mysql_query("UPDATE user SET user_status = 'offline' WHERE username = '$db_user_curr[$looper]'");
        }
        $looper++;
  }
  ?>

When I try to test variables, for example echo $users_day;, it gives my the 2016-12-24 (my current date) .

Also when I test the dates from database it gives me a date with the same type for example I added:

echo $db_user_date[$looper]; 

In my while loop and in some case the date was identical 2016-12-24 when i tested echo strcmp($users_day,$db_user_date[$looper]); it gives me -10 which means they are 100% different but they are not!

Any idea ?

Tom
  • 1,387
  • 3
  • 19
  • 30
M-Amr Moussa
  • 107
  • 1
  • 2
  • 9

2 Answers2

4

Convert your dates to time, which is a numeric value, then compare them.

$current = strtotime($users_day)
$db_date = strtotime($db_user_date[$looper])

if($current > $db_date)
{
    ...
}
Hicaro
  • 687
  • 2
  • 8
  • 21
0

When comparing dates, you should comapre their values, not their string representation. String '01 Jan 2017' is not equal to string '2017-01-01', however, dates are actually equal, right?

Therefore, you need to transform both dates-string into one format so you can compare them safely. The answer by Hicaro handles the problem easily.

Also, consider replacing this whole block of code with a single query:

<?php
mysql_query("UPDATE user SET user_status = 'offline' WHERE DATE(user_lastseen) <> CURDATE()");

So you're setting 'offline' status to all users whose user_lastseen is not equal to today (I assume this is what you're trying to achieve?).

Georgy Ivanov
  • 1,573
  • 1
  • 17
  • 24