Reputation: 21
$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?
Upvotes: 0
Views: 501
Reputation: 101
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
);
Upvotes: 2
Reputation: 379
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);
Upvotes: 2
Reputation: 2352
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()
Upvotes: 3