1

I'm trying to compare 2 dates, by PHP's documentation :

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 > $date2); //false

So now is not bigger than tomorrow, so it's false. Now I have this :

$date_start = \DateTime::createFromFormat('d/m/Y H:i', '18/07/2018 16:20');
$date_start_format = $date_start->format('d/m/Y H:i');

$date_end = \DateTime::createFromFormat('d/m/Y H:i', '01/08/2018 21:45');
date_end_format = $date_end->format('d/m/Y H:i');

var_dump($date_start_format > $date_end_format); //True

Now when I try to compare an ancient date, with tomorrow, like in the example, I get true. Which should return false, can someone please explain why?

4
  • 3
    Even if the date is ancient, if the day is greater than the day of the current date, you will get true. That's why dates are compared in the Y-m-d format when they are strings. Commented Jul 31, 2018 at 9:01
  • Because they are compared as strings? Doesn't format return strings? Commented Jul 31, 2018 at 9:02
  • @AngelPolitis I didn't notice that format() was returning them as strings, thank you! Commented Jul 31, 2018 at 9:05
  • You're welcome @IslamElshobokshy 😊 Commented Jul 31, 2018 at 9:06

2 Answers 2

7

You should compare DateTime objects:

var_dump($date_start > $date_end);
# bool(false)

By comparing the result of the format() method you are comparing strings which is not what you are expecting to do.
To understand, compare your formatted dates character by character:

18/07/2018 16:20
01/08/2018 21:45
^-- 1 > 0
Sign up to request clarification or add additional context in comments.

2 Comments

You didn't have to go all the way through explaining how a string comparison works haha, but thanks alot ! 😊
@IslamElshobokshy A complete explanation can help you understand ;-)
0

Try calculating the time stamp of each date then compare them

var_dump($date1->getTimestamp() > $date2->getTimestamp())

1 Comment

var_dump($date1->getTimestamp() > $date2->getTimestamp())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.