For several different clients we needed to display a schedule of opening hours on their websites. They also wanted to display if a department / store / ... is open on the moment you visit the site. My colleague Seb extracted all the functionality around opening hours to the newly released
You create an
OpeningHours object that describes a business' opening hours. It can be queried for
closed on days or specific dates, or use to present the times per day.
A set of opening hours is created by passing in a regular schedule, and a list of exceptions.
$openingHours = OpeningHours::create([ 'monday' => ['09:00-12:00', '13:00-18:00'], 'tuesday' => ['09:00-12:00', '13:00-18:00'], 'wednesday' => ['09:00-12:00'], 'thursday' => ['09:00-12:00', '13:00-18:00'], 'friday' => ['09:00-12:00', '13:00-20:00'], 'saturday' => ['09:00-12:00', '13:00-16:00'], 'sunday' => , 'exceptions' => [ '2016-11-11' => ['09:00-12:00'], '2016-12-25' => , ], ]);
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'); // false
It 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->isOpenAt(new DateTime('2016-12-25')); // false
It 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(); // OpeningHoursForDay object for a specific day $openingHours->forDate(new DateTime('2016-12-25')); // OpeningHoursForDay of all exceptions, keyed by date $openingHours->exceptions();