How to handle business days in PHP

smknstd
code16
Published in
2 min readApr 17, 2024

When developing a commerce-related application, it’s sometimes necessary to determine whether a point of sale is open or closed on a given day. In addition to having weekly closing days, consideration must also be given to holidays and annual closures for vacations or maintenance, for example. A typical scenario is when allowing a customer to schedule an appointment at their point of sale. It’s essential to prevent the customer from booking on a day when it’s not possible.

Typical example of a booking UX where it is necessary to dynamically indicate closed days for a given point of sales

In PHP, when handling dates, the Carbon library is commonly used. It’s a very powerful tool, but unfortunately, it doesn’t let you manipulate opening or closing days. Therefore, you have to install this additional package:

composer require code16/carbon-business-days

Once installed, you simply create a new object:

$businessDays = new Code16\CarbonBusiness\BusinessDays();

And then you can easily add weekly closing days when weekend is custom for example:

$businessDays
->setWeekendDays([
Carbon::SUNDAY,
Carbon::MONDAY,
]);

As well as closing days like public holidays:

$businessDays
->addHolidays([
Carbon::parse('2024-01-01'), //new year eve
Carbon::parse('2024-05-01'), //labour day
Carbon::parse('2024-05-08'), //victory day
]);

You can also add periods of several consecutive closing days:

//when store is closed for whole july
$businessDays->addClosedPeriod(
from: Carbon::parse('2024-07-01'),
to: Carbon::parse('2024-07-31'),
);

It works great with custom closed periods when you let a point of sales define their own vacations for example:

Example of an admin panel of closed periods for a given point of sales

Then it’s very easy to determine whether a particular day is open or closed:

$isOpened = $businessDays->isOpenedDay(Carbon::tomorrow()); //true or false

You can easily calculate the number of business days between two dates:

$businessDayCount = $businessDays->daysBetween(
from: $rental->start_date,
to: $rental->end_date,
); // returns an int

You can also calculate the date of a future open day. For example, if you need to calculate a date with a certain number of business days:

$end = $businessDays->addDaysTo(
date: Carbon::parse('2024-04-05'),
days: 10
); // returns a Carbon object (something like 2024-04-21)

That’s all folks !

--

--