The translation of PHP DateTime comparison end date is:
P粉920835423
2023-07-31 15:48:47
<p>I'm trying to make a button disabled by comparing today's datetime to a due date in the database, but I'm having a problem. I have made the condition but it doesn't work on 1 day deadline, for example: 2023-07-31 00:00:00 vs. 2023-07-31 00:00:00. <br /><br />Here is the code I tried: </p><p><br /></p>
<pre class="brush:php;toolbar:false;">// Variables
// $request_project->start_date (contains the startdate with datetime data type also user defined)
// $request_project->end_date (contains the deadline with datetime data type also user defined)
$startDate = new DateTime($request_project->start_date); //
$endDate = new DateTime($request_project->end_date);
$startDateTime = date('Y-m-d') . ' 00-00-00';
$endDateTime = date('Y-m-d') . ' 23-59-59';
$startDateString = $startDate->format('Y-m-d H:i:s');
$endDateString = $endDate->format('Y-m-d H:i:s');</pre>
<p>So I want to compare if the user defined due date is less than or equal to today's date time, if so the button will be active and have btn-primary class, otherwise the disabled attribute will be added and btn-primary will be changed to btn -secondary. </p>
<pre class="brush:php;toolbar:false;"><?php if($endDateString <= $endDateTime) {?>
<a href="#" class="btn btn-primary btn-hover w-100 mt-2"
onclick="doSomething()">Apply Now <i class="uil uil-arrow-right"></i></a>
<?php } else { ?>
<a href="#" class="btn btn-secondary btn-hover w-100 mt-2 disabled"
onclick="doSomething()">Apply Now <i class="uil uil-arrow-right">
</i></a>
<?php } ?>
<a href="#" class="btn btn-soft-warning btn-hover w-100 mt-2
bookmark" id="<?=$request_project->id?>"><i class="uil uil-bookmark">
</i> Add Bookmark</a></pre>
<p>Instead of executing the else code block, it always executes the if code block, even if the end_date has expired. </p>
The dilemma you're having seems to be related to how you compare the end date to the current date-time. The problem lies in the way you construct the $endDateTime variable using the date() function.
In your code, you use 'Y-m-d' as the format of date(), which means it only contains year, month and day, no time. You then concatenated '23-59-59' to the date, resulting in a wrong datetime format.
To resolve this issue, you should modify the $endDateTime variable to include the complete time (hours, minutes, and seconds) in the correct format before comparing. You can do this using the date() function in the format 'Y-m-d H:i:s', like this:
Now, $endDateTime will have the correct format and your comparison should work as expected.
The following is the updated code:
With this adjustment, the code should now correctly disable the button when the end date is past today's date.