Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KalimeroMK's avatar

Count even days and not even days in a date range

Hi all

How to count all even and even days in date range, creating some booking app and they have one price for Monday, Wednesday, Friday, Sunday second price for Tuesday, Thursday, Saturday so i need to count two type of days :)

0 likes
7 replies
Snapey's avatar

its the number of days / 2 and then work out if the start day is 'even' or odd'

If the dates are 15th to 25th (inclusive) then this is 11 days

Those 11 days are;

  • 5 odd and 6 even, or
  • 5 even and 6 odd.

The key to this is if the first day of the week is even or odd

Snapey's avatar

Personally, I would set it up so that every day of the week has a different rate, and then seed it with your odd and even rates.

If you cope with every day of the week with a different price then when they come to you and say that saturday and sunday now have their own rates then its an easy fix.

KalimeroMK's avatar

if I use /2 on day and for example the booking id for friday to friday the math is not corect

MichalOravec's avatar
Level 75
$start = Carbon::create(2020, 1, 1);

$end = Carbon::create(2020, 12, 31);

$oddDays = $start->diffInDaysFiltered(function ($date) {
   return $date->isMonday() || 
     $date->isWednesday() || 
     $date->isFriday() || 
     $date->isSunday();
}, $end);

$evenDays = $start->diffInDaysFiltered(function ($date) {
   return $date->isTuesday() || 
     $date->isThursday() || 
     $date->isSaturday();
}, $end);

Or easier

$start = Carbon::create(2020, 1, 1);

$end = Carbon::create(2020, 12, 31);

$oddDays = $start->diffInDaysFiltered(function ($date) {
   return in_array($date->dayOfWeek, [1, 3, 5, 0]);
}, $end);

$evenDays = $start->diffInDaysFiltered(function ($date) {
   return in_array($date->dayOfWeek, [2, 4, 6]);
}, $end);
jlrdw's avatar

Was hoping carbon docs would be used as isMonday, etc is right in the docs. That way @kalimeromk would learn carbon usage. But great answer.

Snapey's avatar

@kalimeromk then you did not read my answer fully

Friday to Friday is 8 days, 4 even and 4 odd.

Please or to participate in this conversation.