Why date comparison gives wrong result?

101
May 28, 2022, at 11:00 AM
$examDay1 = date("07.02.2022");
$examDay2 = date("18.03.2022");
$examDay3 = date("06.04.2022");
$today = date("d.m.Y");
print_r($examDay1 <= $today);  //true 
print_r($examDay2 <= $today);  // false as I expected
print_r($examDay3 <= $today);  // true for some reason

I am trying to give access to users in same specific dates. For example one of them started today and the comparison worked fine. However, somehow it says $examDay3 <=$today gives true. What am I doing wrong?

Answer 1

The date() function in php returns a string so you can't use those operators to compare. If you want to be able to compare dates, something like this would work:

   $examDay1 = new DateTimeImmutable("07.02.2022");
   $examDay2 = new DateTimeImmutable("18.03.2022");
   $examDay3 = new DateTimeImmutable("06.04.2022");
   $today = new DateTimeImmutable('now');
   print_r($examDay1 <= $today);  //true 
   print_r($examDay2 <= $today);  // false 
   print_r($examDay3 <= $today);  // false

If you prefer the procedural style, you can use date_create_immutable() instead of new DateTimeImmutable()

Answer 2

You may use dateTime class. The method DateTime::createFromFormat can be usefull. Try :

$examDay1 = DateTime::createFromFormat('j.m.Y', '07.02.2022');
$examDay2 = DateTime::createFromFormat('j.m.Y', '18.03.2022');
$examDay3 = DateTime::createFromFormat('j.m.Y', '06.04.2022');
$today = new DateTime("now");;
print_r($examDay1 <= $today);  
print_r($examDay2 <= $today);  
print_r($examDay3 <= $today);  
Answer 3

PHPs Date function returns a string, as stated in the documentation:

You can use "strtotime" to convert the date string to a timestamp integer, and use it for comparison.

$examDay1 = date("07.02.2022");
$examDay2 = date("18.03.2022");
$examDay3 = date("06.04.2022");
$today = time();
var_dump(
    strtotime($examDay1) <= $today,
    strtotime($examDay2) <= $today,
    strtotime($examDay3) <= $today
);
Rent Charter Buses Company
READ ALSO
How we can insert header and footer in google docs with google docs api using PHP code

How we can insert header and footer in google docs with google docs api using PHP code

I want to insert header and footer in my google docs with google docs api in PHP codeI am doing it like this-

79
Merge people profiles based on email match

Merge people profiles based on email match

I have an existing directory (php with xml datasource) which contains people information such as this:

113
Writing a new and appending a file in PHP without erasing contents

Writing a new and appending a file in PHP without erasing contents

How could one write a new line to a file in php without erasing all the other contents of the file?

101