Search code examples
phpdatedayofweekdate-difference

How to finding the number of days between two days of the week?


How to find the number of days between two days not dates using PHP?

I know how to get the number of days between two dates, but my input values are day names (date-ignorant).

Inputs/Outputs:

Wednesday and Saturday returns 3

Sunday and Wednesday returns 3


Solution

  • Your task doesn't seem to require date functions at all. A simple lookup array will suffice.

    1. Subtract the starting day's integer value from the ending day's integer.
    2. If the difference would be zero or less, add 7 to always return the correct, positive day count.

    Code: (Demo)

    function daysUntil($start, $end) {
        $lookup = [
            'Sunday' => 0,
            'Monday' => 1,
            'Tuesday' => 2,
            'Wednesday' => 3,
            'Thursday' => 4,
            'Friday' => 5,
            'Saturday' => 6
        ];
        $days = $lookup[$end] - $lookup[$start] + ($lookup[$end] <= $lookup[$start] ? 7 : 0);
        return "{$days} days from {$start} to {$end}\n";
    }
    
    echo daysUntil('Wednesday', 'Saturday');  // Thursday, Friday, Saturday
    echo daysUntil('Monday', 'Friday');       // Tuesday, Wednesday, Thursday, Friday
    echo daysUntil('Thursday', 'Thursday');   // [assumed next week]
    echo daysUntil('Friday', 'Monday');       // Saturday, Sunday, Monday
    echo daysUntil('Saturday', 'Sunday');     // Sunday
    echo daysUntil('Sunday', 'Saturday');     // Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
    echo daysUntil('Sunday', 'Wednesday');    // Monday, Tuesday, Wednesday
    

    Output:

    3 days from Wednesday to Saturday
    4 days from Monday to Friday
    7 days from Thursday to Thursday
    3 days from Friday to Monday
    1 days from Saturday to Sunday
    6 days from Sunday to Saturday
    3 days from Sunday to Wednesday
    

    Or you can replace the lookup array with 4 function calls and achieve the same outcome: (Demo)

    function daysUntil($start, $end) {
        $days = date('w', strtotime($end)) - date('w', strtotime($start));
        $days += $days < 1 ? 7 : 0;
        return "{$days} days from {$start} to {$end}\n";
    }