0

I'm want to know which date is the greater date

<?php
$date1=16/05/19;
$date2=19/04/19;

if ($date1 > $date2) {
    echo 'date1 greater than date2';
else {
    echo 'Less than';
}

Why do I get "Less than"?

Robert
  • 7,394
  • 40
  • 45
  • 64
  • 2
    Quick guess: you are comparing Strings, not actual Date objects, and Strings are compared alphabetically (actually asciibetically). 16 is smaller than 19. – Robert May 16 '19 at 20:53
  • 2
    Possible duplicate of [How do I compare two DateTime objects in PHP 5.2.8?](https://stackoverflow.com/questions/961074/how-do-i-compare-two-datetime-objects-in-php-5-2-8) –  May 16 '19 at 21:00
  • Also, use full 4-digit year ... 19 could be day 19 or 2019 .. 16 could be day 16 or 2016... @tim that's a good resource, however performing a strtotime($date1) > strtotime($date2) is just as easy... – Raphioly-San May 16 '19 at 21:01
  • no its bad strtotime shouldn't be used @Raphioly-San –  May 16 '19 at 21:06
  • Never meant to say strtotime is the way to go, however it is a relatively easy to use function if you're in a "don't care" situation and it's got it right most of the times, if date is formatted correctly... I do think "don't care" may be a little bit the case here ;) Otherwise, he's got your resource... Talking best practice? Then we'll take it somewhere else, 'aight ;) – Raphioly-San May 16 '19 at 21:13
  • you are missing a bracket `}else {` too (this will not answer the question, just a hint) – GabrieleMartini May 16 '19 at 21:17

2 Answers2

1
<?php
    $date1=new DateTime("16-05-2019");
    $date2=new DateTime("19-04-2019");

   if ($date1 > $date2) {
      echo 'date1 greater than date2';
   } else {
      echo 'Less than';
   }
?>

Here you compare two date objects (see https://www.php.net/manual/en/function.date.php)

GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26
0

Thanks fo you all guys!

now I have new problem :

        $last_update=0;
          foreach($datetimetextresult as $value1){
           $datetime_text = date("d-m-Y", strtotime($value1->datetime));
           $date1=new DateTime ($datetime_text);
           $text = $value1->text;
            if ($last_update <$date1){
              $last_update=$date1;
              $last_text = $text ; 
            }

}

I get this eror: "Object of class DateTime could not be converted to int"