Query and format a set of opening hours
With spatie/opening-hours you create an object that describes a business' opening hours, which you can query for open or closed on days or specific dates, or use to present the times per day.
spatie/opening-hours can be used directly on Carbon thanks
to cmixin/business-time so you can benefit
opening hours features directly on your enhanced date objects.
A set of opening hours is created by passing in a regular schedule, and a list of exceptions.
…The object can be queried for a day in the week, which will return a result based on the regular schedule:
// Open on Mondays:
$openingHours->isOpenOn('monday'); // true
// Closed on Sundays:
$openingHours->isOpenOn('sunday'); // falseIt can also be queried for a specific date and time:
// Closed because it's after hours:
$openingHours->isOpenAt(new DateTime('2016-09-26 19:00:00')); // false
// Closed because Christmas was set as an exception
$openingHours->isOpenOn('2016-12-25'); // falseIt can also return arrays of opening hours for a week or a day:
// OpeningHoursForDay object for the regular schedule
$openingHours->forDay('monday');
// OpeningHoursForDay[] for the regular schedule, keyed by day name
$openingHours->forWeek();
// Array of day with same schedule for the regular schedule, keyed by day name, days combined by working hours
$openingHours->forWeekCombined();
// OpeningHoursForDay object for a specific day
$openingHours->forDate(new DateTime('2016-12-25'));
// OpeningHoursForDay[] of all exceptions, keyed by date
$openingHours->exceptions();On construction, you can set a flag for overflowing times across days. For example, for a nightclub opens until 3am on Friday and Saturday:
$openingHours = \Spatie\OpeningHours\OpeningHours::create([
'overflow' => true,
'friday' => ['20:00-03:00'],
'saturday' => ['20:00-03:00'],
], null);This allows the API to further at previous day's data to check if the opening hours are open from its time range.
You can add data in definitions then retrieve them:
…In the example above, data are strings but it can be any kind of value. So you can embed multiple properties in an array.
For structure convenience, the data-hours couple can be a fully-associative array, so the example above is strictly equivalent to the following:
…You can use the separator to to specify multiple days at once, for the week or for exceptions:
$openingHours = OpeningHours::create([
'monday to friday' => ['09:00-19:00'],
'saturday to sunday' => [],
'exceptions' => [
// Every year
'12-24 to 12-26' => [
'hours' => [],
'data' => 'Holidays',
],
// Only happening in 2024
'2024-06-25 to 2024-07-01' => [
'hours' => [],
'data' => 'Closed for works',
],
],
]);The last structure tool is the filter, it allows you to pass closures (or callable function/method reference) that take a date as a parameter and returns the settings for the given date.
…If a callable is found in the "exceptions" property, it will be added automatically to filters so you can mix filters and exceptions both in the exceptions array. The first filter that returns a non-null value will have precedence over the next filters and the filters array has precedence over the filters inside the exceptions array.
Warning: We will loop on all filters for each date from which we need to retrieve opening hours and can neither predicate nor cache the result (can be a random function) so you must be careful with filters, too many filters or long process inside filters can have a significant impact on the performance.
It can also return the next open or close DateTime from a given DateTime.
…Read the usage section for the full api.
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
You can install the package via composer:
composer require spatie/opening-hoursThe package should only be used through the OpeningHours class. There are also three value object classes used throughout, Time, which represents a single time, TimeRange, which represents a period with a start and an end, and openingHoursForDay, which represents a set of TimeRanges which can't overlap.
Spatie\OpeningHours\OpeningHoursOpeningHours::create(array $data, $timezone = null, $outputTimezone = null): OpeningHoursStatic factory method to fill the set of opening hours.
$openingHours = OpeningHours::create([
'monday' => ['09:00-12:00', '13:00-18:00'],
// ...
]);If no timezone is specified, OpeningHours will just assume you always
pass DateTime objects that have already the timezone matching your schedule.
If you pass a $timezone as a second argument or via the array-key 'timezone'
(it can be either a DateTimeZone object or a string), then passed dates will
be converted to this timezone at the beginning of each method, then if the method
return a date object (such as nextOpen, nextClose, previousOpen,
previousClose, currentOpenRangeStart or currentOpenRangeEnd), then it's
converted back to original timezone before output so the object can reflect
a moment in user local time while OpeningHours can stick in its own business
timezone.
Alternatively you can also specify both input and output timezone (using second and third argument) or using an array:
$openingHours = OpeningHours::create([
'monday' => ['09:00-12:00', '13:00-18:00'],
'timezone' => [
'input' => 'America/New_York',
'output' => 'Europe/Oslo',
],
]);OpeningHours::mergeOverlappingRanges(array $data, bool $ignoreData, array $excludedKeys): arrayFor safety sake, creating OpeningHours object with overlapping ranges will throw an exception unless you pass explicitly 'overflow' => true, in the opening hours array definition. You can also explicitly merge them.
$ranges = [
'monday' => ['08:00-11:00', '10:00-12:00'],
];
$mergedRanges = OpeningHours::mergeOverlappingRanges($ranges); // Monday becomes ['08:00-12:00']
OpeningHours::create($mergedRanges);
// Or use the following shortcut to create from ranges that possibly overlap:
OpeningHours::createAndMergeOverlappingRanges($ranges);Not all days are mandatory, if a day is missing, it will be set as closed.
OpeningHours::forWeek(): Spatie\OpeningHours\OpeningHoursForDay[]Returns an array of OpeningHoursForDay objects for a regular week.
$openingHours->forWeek();OpeningHours::forWeekCombined(): arrayReturns an array of days. Array key is first day with same hours, array values are days that have the same working hours and OpeningHoursForDay object.
$openingHours->forWeekCombined();OpeningHours::forWeekConsecutiveDays(): arrayReturns an array of concatenated days, adjacent days with the same hours. Array key is first day with same hours, array values are days that have the same working hours and OpeningHoursForDay object.
Warning: consecutive days are considered from Monday to Sunday without looping (Monday is not consecutive to Sunday) no matter the days order in initial data.
$openingHours->forWeekConsecutiveDays();OpeningHours::forDay(string $day): Spatie\OpeningHours\OpeningHoursForDayReturns an OpeningHoursForDay object for a regular day. A day is lowercase string of the english day name.
$openingHours->forDay('monday');OpeningHours::forDate(DateTimeInterface $dateTime): Spatie\OpeningHours\OpeningHoursForDayReturns an OpeningHoursForDay object for a specific date. It looks for an exception on that day, and otherwise it returns the opening hours based on the regular schedule.
$openingHours->forDate(new DateTime('2016-12-25'));OpeningHours::exceptions(): Spatie\OpeningHours\OpeningHoursForDay[]Returns an array of all OpeningHoursForDay objects for exceptions, keyed by a Y-m-d date string.
$openingHours->exceptions();OpeningHours::isOpenOn(string $day): boolChecks if the business is open (contains at least 1 range of open hours) on a day in the regular schedule.
$openingHours->isOpenOn('saturday');If the given string is a date, it will check if it's open (contains at least 1 range of open hours) considering both regular day schedule and possible exceptions.
$openingHours->isOpenOn('2020-09-03');
$openingHours->isOpenOn('09-03'); // If year is omitted, current year is used insteadOpeningHours::isClosedOn(string $day): boolChecks if the business is closed on a day in the regular schedule.
$openingHours->isClosedOn('sunday');OpeningHours::isOpenAt(DateTimeInterface $dateTime): boolChecks if the business is open on a specific day, at a specific time.
$openingHours->isOpenAt(new DateTime('2016-26-09 20:00'));OpeningHours::isClosedAt(DateTimeInterface $dateTime): boolChecks if the business is closed on a specific day, at a specific time.
$openingHours->isClosedAt(new DateTime('2016-26-09 20:00'));OpeningHours::isOpen(): boolChecks if the business is open right now.
$openingHours->isOpen();OpeningHours::isClosed(): boolChecks if the business is closed right now.
$openingHours->isClosed();OpeningHours::isAlwaysOpen(): boolChecks if the business is open 24/7, has no exceptions and no filters.
if ($openingHours->isAlwaysOpen()) {
echo 'This business is open all day long every day.';
}OpeningHours::isAlwaysClosed(): boolChecks if the business is never open, has no exceptions and no filters.
OpeningHours accept empty array or list with every week day empty with no prejudices.
If it's not a valid state in your domain, you should use this method to throw an exception or show an error.
if ($openingHours->isAlwaysClosed()) {
throw new RuntimeException('Opening hours missing');
}OpeningHours::nextOpenOpeningHours::nextOpen(
?DateTimeInterface $dateTime = null,
?DateTimeInterface $searchUntil = null,
?DateTimeInterface $cap = null,
) : DateTimeInterface`Returns next open DateTime from the given DateTime ($dateTime or from now if this parameter is null or omitted).
If a DateTimeImmutable object is passed, a DateTimeImmutable object is returned.
Set $searchUntil to a date to throw an exception if no open time can be found before this moment.
Set $cap to a date so if no open time can be found before this moment, $cap is returned.
$openingHours->nextOpen(new DateTime('2016-12-24 11:00:00'));OpeningHours::nextCloseOpeningHours::nextClose(
?DateTimeInterface $dateTime = null,
?DateTimeInterface $searchUntil = null,
?DateTimeInterface $cap = null,
) : DateTimeInterface`Returns next close DateTime from the given DateTime ($dateTime or from now if this parameter is null or omitted).
If a DateTimeImmutable object is passed, a `DateTimeImmu
No open issues yet, or sync has not completed.