PHP - How to compare a date that comes from the Mysql database to the current day?

Asked

Viewed 4,580 times

1

I have a column in the database which is in format DATE (Y-m-d). In php code I recover this string and have to compare with the current date and this is the condition I am 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.

  • Everything seems to be okay: 2016-05-30 and 2016-07-02. That’s why I don’t understand.

  • The one sought by the class Datetime

  • Hi John, it’s not the same question. I had already passed through it before asking. Note the answer that has 16 points. It’s exactly what I did and it’s not working. if(strtotime($data1) > strtotime($data2)). The answer that worked was Nelson’s. One has to pass to string and the other not.

2 answers

1

One way to do this is by using the object Datetime, and check the number in "timestamp" format, 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
} 

1


Actually just remove 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.

Exit 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"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.