[FIXED] What PHP is needed to calculate due date from todays date

Issue

I need a few if/elseif/else statements (which I loosely understand) to display different things based on how far away a due date is from today. Example below:

  • If due date is > 4 weeks away, priority is low
  • If due date is < 4 weeks and > 2 weeks away, priority is medium
  • If due date is < 2 weeks and > 1 week away, priority is high
  • If due date is < 1 week away, priority is critical

Edited to add: the due date will vary across projects. I am trying to create a project management dashboard. So I am trying to compare $dt = new DateTime($Project[due_date]); to $today = new DateTime();

When I write out

if($dt < $today) {
    echo 'urgent';
} else {
    echo 'high';
}

I keep getting this error:

Catchable fatal error: Object of class DateTime could not be converted to string

Forgive me if this is a poorly written or newbie question, I am very new to PHP (HTML/CSS is my strength) so I am having a hard time knowing what to even Google to help me.

Solution

Please try next code:

<?php
$dt = new DateTime($Project['due_date']); 

$diff_in_weeks = $dt->diff(new DateTime())->format('%a')/7;

switch (true) {
    case $diff_in_weeks > 4:
        echo 'low';
        break;
    case $diff_in_weeks > 2:
        echo 'medium';
        break;
    case $diff_in_weeks > 1:
        echo 'high';
        break;
    default:
        echo 'critical';
} 

PHP online editor

Answered By – Slava Rozhnev

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published