PHP - How to compare a date that comes from the MySql database with the current day? [duplicate]

1

I have a column in the database that is in DATE (Y-m-d) format. In the php code I retrieve this string and I have to compare it with the current date and this is the condition I'm using:

$dtEntrega=date("Y-m-d",strtotime($row["dtEnterga"])); 
$today = strtotime(date("Y-m-d")); 

if($today>=$dtEntrega){
//Fazer algo
} 

But this code always returns true, even if the delivery date is stored in the database with date in the future. Does anyone know where I'm going wrong or is something missing?

Edition: The question is not the same as the one quoted by the moderator because the result of that does not apply to my context.

    
asked by anonymous 30.05.2016 / 22:45

2 answers

1

In fact, just remove the strtotime from the variable $ today:

<?php

   $dtEntrega=date("Y-m-d",strtotime($row["dtEnterga"])); 
   $today = date("Y-m-d"); 
   if($today>=$dtEntrega){
      echo ' alguma coisa';
   }

When this occurs a var_dump in the variable would already elucidate the problem.

Output before correction:

  $dtEntrega ===> string(10) "2016-05-30"
  $today    ===> int(1464652800) 

After correction:

  $dtEntrega ===> string(10) "2016-05-30"
  $today    ===> string(10) "2016-05-30"
    
31.05.2016 / 02:33
1

One way to do this is to use the DateTime object, and check the number in " timestamp ", just resetting the milliseconds:

$dataAtual = new DateTime();

function formatDateObj($dateString) {
    $dateString = new DateTime($dateString);
    $dateString->format('Y-m-d H:i:s.uO'); 
    return $dateString;
}

$dataEntrega = formatDateObj($row["dtEnterga"].' 00:00:00');

if ($dataAtual->getTimestamp() >= $dateEntrega->getTimestamp()) {
   //Fazer algo
} 
    
30.05.2016 / 23:24