florianv / business
DateTime calculations in business hours
Installs: 694 128
Dependents: 1
Suggesters: 0
Security: 0
Stars: 361
Watchers: 9
Forks: 25
Open Issues: 4
Requires
- php: >=8.0
- ext-json: *
Requires (Dev)
- jeremeamia/superclosure: ^2.1
- phpunit/phpunit: ^9.0.0
Suggests
- jeremeamia/superclosure: Allows to serialize special days
This package is auto-updated.
Last update: 2024-10-13 12:42:49 UTC
README
DateTime calculations in business hours
Installation
$ composer require florianv/business
Usage
First you need to configure your business schedule:
use Business\SpecialDay; use Business\Day; use Business\Days; use Business\Business; use Business\Holidays; use Business\DateRange; // Opening hours for each week day. If not specified, it is considered closed $days = [ // Standard days with fixed opening hours new Day(Days::MONDAY, [['09:00', '13:00'], ['2pm', '5 PM']]), new Day(Days::TUESDAY, [['9 AM', '5 PM']]), new Day(Days::WEDNESDAY, [['10:00', '13:00'], ['14:00', '17:00']]), new Day(Days::THURSDAY, [['10 AM', '5 PM']]), // Special day with dynamic opening hours depending on the date new SpecialDay(Days::FRIDAY, function (\DateTime $date) { if ('2015-05-29' === $date->format('Y-m-d')) { return [['9 AM', '12:00']]; } return [['9 AM', '5 PM']]; }), ]; // Optional holiday dates $holidays = new Holidays([ new \DateTime('2015-01-01'), new \DateTime('2015-01-02'), new DateRange(new \DateTime('2015-07-08'), new \DateTime('2015-07-11')), ]); // Optional business timezone $timezone = new \DateTimeZone('Europe/Paris'); // Create a new Business instance $business = new Business($days, $holidays, $timezone);
Methods
within() - Tells if a date is within business hours
$bool = $business->within(new \DateTime('2015-05-11 10:00'));
timeline() - Returns a timeline of business dates
$start = new \DateTime('2015-05-11 10:00'); $end = new \DateTime('2015-05-14 10:00'); $interval = new \DateInterval('P1D'); $dates = $business->timeline($start, $end, $interval);
closest() - Returns the closest business date from a given date
// After that date (including it) $nextDate = $business->closest(new \DateTime('2015-05-11 10:00')); // Before that date (including it) $lastDate = $business->closest(new \DateTime('2015-05-11 10:00'), Business::CLOSEST_LAST);
Serialization
PHP serialization
The Business
class can be serialized so it can be stored for later reuse:
$serialized = serialize($business); $business = unserialize($serialized);
If you use SpecialDay
instances, you need to install the jeremeamia/superclosure
library providing closure serialization:
$ composer require jeremeamia/superclosure
JSON serialization
All classes can be encoded to JSON
$json = json_encode($business);
The SpecialDay
instances require a context in order extract the data from the callable.
This is automatically set to new \DateTime('now')
for json_encode()
call only.