florianv/business

工作时间内日期计算

v2.0.0 2022-06-13 07:41 UTC

This package is auto-updated.

Last update: 2024-09-13 12:32:07 UTC


README

工作时间内日期计算

安装

$ composer require florianv/business

使用

首先,您需要配置您的业务时间表

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);

方法

within() - 判断一个日期是否在工作时间内
$bool = $business->within(new \DateTime('2015-05-11 10:00'));
timeline() - 返回业务日期的时间轴
$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() - 返回给定日期最近的业务日期
// 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);

序列化

PHP序列化

Business类可以被序列化,以便以后重用

$serialized = serialize($business);
$business = unserialize($serialized);

如果您使用SpecialDay实例,您需要安装提供闭包序列化的jeremeamia/superclosure

$ composer require jeremeamia/superclosure

JSON序列化

所有类都可以被编码成JSON

$json = json_encode($business);

SpecialDay实例需要上下文才能从可调用对象中提取数据。对于json_encode()调用,这自动设置为new \DateTime('now')

许可证

MIT