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
Your task doesn't seem to require date functions at all. A simple lookup array will suffice.
- Subtract the starting day's integer value from the ending day's integer.
- 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";
}
Use the PHP date_diff()
function (docs).
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%d'); // For days
Per the clarification, you could create arbitrary Saturdays and Wednesdays to calculate it:
$datetime1 = date_create(date('Y-m-d',strtotime('wednesday')));
$datetime2 = date_create(date('Y-m-d',strtotime('saturday')));
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%d'); // For days
Would return "3", but depending when you ran it.
You can write the name of the day for parsing in a new DateTime class:
<?php
$datetime1 = new DateTime('Sunday');
$datetime2 = new DateTime('Wednesday');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Also below the one line version:
echo (new DateTime('Sunday'))->diff(new DateTime('Wednesday'))->format('%a days');