John Davidson

php - Why date comparison gives wrong result?

0 comments
Message:


$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?



My Answer:
The issue is that you are comparing dates as strings, which may not give you the expected results. When you use the `date()` function in PHP, it returns a string representation of the current date or the date specified in the format you provided.

To compare dates correctly, you should convert the dates to Unix timestamps using the `strtotime()` function. Here's how you can modify your code:

php
$examDay1 = strtotime("07.02.2022");
$examDay2 = strtotime("18.03.2022");
$examDay3 = strtotime("06.04.2022");
$today = strtotime(date("d.m.Y"));

print_r($examDay1 <= $today); // false
print_r($examDay2 <= $today); // false
print_r($examDay3 <= $today); // false


By converting the dates to Unix timestamps, you can accurately compare them and get the expected results.

Rate this post

4 of 5 based on 3157 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us