phpdatetimeif-statementdate-comparison

Determine if given date is less than 1 day old, 1 to 3 days old, or more


I need make if like --->

if your activity is less than 1 day do something

else if your activity is more than 1 day and less than 3 do something else

else if your activity is more than 3 do something else

I need this in PHP. My actual code is:

if (strtotime(strtotime($last_log)) < strtotime('-1 day') ) {
    $prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive less than 1 day") . ",";
} else if (strtotime($last_log) > strtotime('-1 day') && strtotime($last_log) < strtotime('-3 day')) {
    $prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 1 day and less than 3 days") . ",";
} else if (strtotime($last_log) > strtotime('-3 day')) {
    $prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 3") . ",";
}

I think I really don't understand date calculations.


Solution

  • The date_diff is much easier in this case (http://php.net/manual/en/function.date-diff.php):

    $datetime1 = date_create(); // now
    $datetime2 = date_create($last_log);
        
    $interval = date_diff($datetime1, $datetime2);
    
    // number of days between your last login and now
    $days = $interval->format('%a');
    
    // difference (only) in days
    // (2023-11-05 and 2024-01-08 will return 3 because 05 and 08 are seperated by 3 days.
    $days = $interval->format('%d');
    

    For more formats see: https://www.php.net/manual/en/dateinterval.format.php

    Or in your way:

    if (strtotime($last_log) < strtotime('-1 day')){
        // it's been longer than one day
    }