Issue
I am comparing two dates with the current date, but the problem only occurs if the start date and the current date are the same. If both the start date and the current date are the same, the output is in progress
, but there is logic that past
is shown.
Below is my code
$endDate = new DateTime($row['end_date']);
$startDate = new DateTime($row['start_date']);
$current_date = new DateTime();
if ($startDate < $current_date){
if($endDate < $current_date){
$row["status"] = "past";
}else if ($endDate == $current_date){
$row["status"] = "in progress";
}other than that{
$row["status"] = "in progress";
}
}else if ($startDate > $current_date){
$row["status"] = "upcoming";
}else if ($startDate == $current_date){
$row["status"] = "in progress";
}other than that{
$row["status"] = "in progress";
}
Actual value example:
start date = "27-02-2023"
End Date = "27-02-2023"
Current date = "27-02-2023"
Shows “past” instead of “in progress”
Solution
The issue you’re facing is because the date comparison in your code is based on the date and time, not just the date, as mentioned in the comments.
To fix this, you can modify your code to only compare the dates, without the time component. You can use the setTime() method to set the time to midnight for both the start and end dates, like this:
$endDate = (new DateTime($row['end_date']))->setTime(0, 0, 0);
$startDate = (new DateTime($row['start_date']))->setTime(0, 0, 0);
$current_date = (new DateTime())->setTime(0, 0, 0);
This will set the time for all three dates to midnight, so the comparison will only consider the date component.
Hope this clarifies it.
Answered By – b. Arttour
Answer Checked By – Gilberto Lyons (Easybugfix Admin)