cmixin/business-time

处理工作日和营业时间的Carbon混入

1.14.0 2024-07-01 14:46 UTC

README

Carbon 混入用于处理工作日和营业时间

Latest Stable Version GitHub Actions Code Climate Test Coverage StyleCI

现在可以获取nesbot/carbon的专业支持

安装

composer require cmixin/business-time

用法

首先在应用的全局引导位置加载混入

<?php

use Carbon\Carbon;
use Cmixin\BusinessTime;

BusinessTime::enable(Carbon::class);
// Or if you use Laravel:
// BusinessTime::enable('Illuminate\Support\Carbon');

// And you can enable multiple classes at once:
BusinessTime::enable([
    Carbon::class,
    CarbonImmutable::class,
]);

// As a second argument you can set default opening hours:
BusinessTime::enable(Carbon::class, [
  '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' => [],
    '01-01' => [], // Recurring on each 1st of january
    '12-25' => ['09:00-12:00'], // Recurring on each 25th of december
  ],
  // You can use the holidays provided by BusinessDay
  // and mark them as fully closed days using 'holidaysAreClosed'
  'holidaysAreClosed' => true,
  // Note that exceptions will still have the precedence over
  // the holidaysAreClosed option.
  'holidays' => [
    'region' => 'us-ny', // Load the official list of holidays from USA - New York
    'with' => [
      'labor-day' => null, // Remove the Labor Day (so the business is open)
      'company-special-holiday' => '04-07', // Add some custom holiday of your company 
    ],
  ],
]);

在实时编辑器中尝试

工作日方法现在在任何后续使用的Carbon实例上可用。

功能

通过启用BusinessTime,您可以自动享受BusinessDay的每个假期功能,请参阅cmixin/business-day

一旦设置了营业时间(使用BusinessTime::enable()的第二个参数、Carbon::setOpeningHours([...])$carbonDate->setOpeningHours([...])),您就可以在任何Carbon实例或静态地检索营业时间($carbonDate->getOpeningHours()Carbon::getOpeningHours())作为OpeningHoursspatie/opening-hours)的实例,请参阅spatie/opening-hours以获取此类的完整功能列表。

然后,使用营业时间,您可以直接在Carbon实例上获取以下方法

假日

默认情况下,假日没有特定的营业时间,它将使用当前星期的每日营业时间,但您可以使用'holidaysAreClosed' => true选项关闭每个未在'exceptions'选项中指定的假日业务。否则,您可以使用自定义异常处理程序来关联假日或任何动态计算,如下所示

BusinessTime::enable(Carbon::class, [
  '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' => [
    function (Carbon $date) {
      if ($date->isHoliday()) {
        // Or use ->isObservedHoliday() and set observed holidays:
        // https://github.com/kylekatarnls/business-day#setobservedholidayszone
        switch ($date->getHolidayId()) {
          // If the ID "christmas" exists in the selected holidays region and matches the current date:
          case 'christmas':
            return ['10:00-12:00'];
          default:
            return []; // All other holidays are closed all day long
            // Here you can also pass context data:
            return [
              'hours' => [],
              'data'  => [
                'reason' => 'Today is ' . $date->getHolidayName(),
              ],
            ];
        }
      }
      // Else, typical day => use days of week settings
    },
  ],
]);

Carbon::setHolidaysRegion('us-national');
Carbon::parse('2018-12-25 11:00')->isOpen(); // true  matches custom opening hours of Christmas
Carbon::parse('2018-12-25 13:00')->isOpen(); // false
Carbon::parse('2019-01-01 11:00')->isOpen(); // false closed all day long
Carbon::parse('2019-01-02 11:00')->isOpen(); // true  not an holiday in us-national region, so it's open as any common wednesday

在实时编辑器中尝试

多个营业时间

要处理多个时间表或在不全局加载混入到Carbon的情况下使用所有功能,您可以创建Schedule实例

use Carbon\CarbonImmutable;
use BusinessTime\Schedule;

$us = Schedule::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'],
    'holidaysAreClosed' => true,
    'holidays'          => [
        'region' => 'us-ny',
        'with'   => [
            'labor-day'               => null,
            'company-special-holiday' => '04-07',
        ],
    ],
]);

$fr = Schedule::create([
    'monday'            => ['08:00-12:00', '13:00-17:00'],
    'tuesday'           => ['08:00-12:00', '13:00-17:00'],
    'wednesday'         => ['08:00-12:00'],
    'thursday'          => ['08:00-12:00', '13:00-17:00'],
    'friday'            => ['08:00-12:00', '13:00-17:00'],
    'holidaysAreClosed' => true,
    'holidays'          => [
        'region' => 'fr-national',
        'with'   => [
            'company-special-holiday' => '24/8',
        ],
    ],
]);

$d = CarbonImmutable::parse('2022-10-21 06:40:00');
echo $us->subOpenHours($d, 1)->format('Y-m-d H:i:s'); // 2022-10-20 17:00:00
echo $fr->subOpenHours($d, 1)->format('Y-m-d H:i:s'); // 2022-10-20 16:00:00

$d = CarbonImmutable::parse('2022-10-20 17:30:00');
var_dump($us->isOpen($d)); // true
var_dump($fr->isOpen($d)); // false

在实时编辑器中尝试

isOpenOn

允许您知道业务是否在给定的某天正常营业。

Carbon::isOpenOn('monday') // Returns true if there is at least 1 open range of
                           // hours set for Monday (in the regular schedule)
                           // Carbon::MONDAY would also works

$date->isOpenOn('monday') // Same as above but using local config of $date

Carbon::isOpenOn('2020-09-03') // Returns true if there is at least 1 open range of
                               // hours set for the date 2020-09-03 (considering both
                               // the regular schedule and the exceptions)

isClosedOn

isOpenOn的对立面

Carbon::isClosedOn('monday')
Carbon::isClosedOn('2020-09-03')
$date->isClosedOn('monday')

isOpen

允许您知道业务是否在给定的时刻正常营业。

Carbon::isOpen()       // returns true if the business is now open
$carbonDate->isOpen()  // returns true if the business is open at the current date and time

if (Carbon::isOpen()) {
  $closingTime = Carbon::nextClose()->isoFormat('LT');
  echo "It's now open and until $closingTime.";
}

isClosed

isOpen的对立面

Carbon::isClosed()       // returns true if the business is now closed
$carbonDate->isClosed()  // returns true if the business is closed at the current date and time

if (Carbon::isClosed()) {
  $openingTime = Carbon::nextClose()->calendar();
  echo "It's now closed and will re-open $openingTime.";
}

nextOpen

转到下一个营业时间。

Carbon::nextOpen()       // go to next open time from now
$carbonDate->nextOpen()  // go to next open time from $carbonDate

nextClose

转到下一个非营业时间。

Carbon::nextClose()       // go to next close time from now
$carbonDate->nextClose()  // go to next close time from $carbonDate

previousOpen

转到上一个营业时间。

Carbon::previousOpen()       // go to previous open time from now
$carbonDate->previousOpen()  // go to previous open time from $carbonDate

previousClose

转到上一个非营业时间。

Carbon::previousClose()       // go to previous close time from now
$carbonDate->previousClose()  // go to previous close time from $carbonDate

addOpenTime

添加给定的时间间隔,仅考虑营业时间范围。

例如,如果当前天的营业时间为["09:00-12:00", "13:30-17:00"],在上午11点添加2小时营业时间实际上会添加3小时30分钟(跳过午休:一个半小时),并将时间设置为14:30。

Carbon::addOpenTime('2 hours and 30 minutes')      // add 2 hours and 30 minutes to now
$carbonDate->addOpenTime('2 hours and 30 minutes') // add 2 hours and 30 minutes to $carbonDate

// Can be used with the same interval definitions than add/sub methods of Carbon
$carbonDate->addOpenTime(235, 'seconds')
$carbonDate->addOpenTime(new DateInterval('PT1H23M45S'))
$carbonDate->addOpenTime(CarbonInterval::hours(3)->minutes(20))

$carbonDate->addOpenTime('2 hours and 30 minutes', BusinessTime::HOLIDAYS_ARE_CLOSED)
// add 2 hours and 30 minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

addOpenHours

添加给定的小时数,仅考虑营业时间范围。

Carbon::addOpenHours(3)      // add 3 open hours to now
$carbonDate->addOpenHours(3) // add 3 open hours to $carbonDate


$carbonDate->addOpenHours(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// add 3 open hours considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

addOpenMinutes

添加给定的分钟数,仅考虑营业时间范围。

Carbon::addOpenMinutes(3)      // add 3 open minutes to now
$carbonDate->addOpenMinutes(3) // add 3 open minutes to $carbonDate


$carbonDate->addOpenMinutes(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// add 3 open minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

addClosedTime

添加给定的时间间隔,仅考虑非营业时间范围。

Carbon::addClosedTime('2 hours and 30 minutes')      // add 2 hours and 30 minutes to now
$carbonDate->addClosedTime('2 hours and 30 minutes') // add 2 hours and 30 minutes to $carbonDate

// Can be used with the same interval definitions than add/sub methods of Carbon
$carbonDate->addClosedTime(235, 'seconds')
$carbonDate->addClosedTime(new DateInterval('PT1H23M45S'))
$carbonDate->addClosedTime(CarbonInterval::hours(3)->minutes(20))

$carbonDate->addClosedTime('2 hours and 30 minutes', BusinessTime::HOLIDAYS_ARE_CLOSED)
// add 2 hours and 30 minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

addClosedHours

添加给定的小时数,仅考虑非营业时间范围。

Carbon::addClosedHours(3)      // add 3 closed hours to now
$carbonDate->addClosedHours(3) // add 3 closed hours to $carbonDate


$carbonDate->addClosedHours(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// add 3 closed hours considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

addClosedMinutes

添加给定的分钟数,仅考虑非营业时间范围。

Carbon::addClosedMinutes(3)      // add 3 closed minutes to now
$carbonDate->addClosedMinutes(3) // add 3 closed minutes to $carbonDate


$carbonDate->addClosedMinutes(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// add 3 closed minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

subOpenTime

减去给定的时间间隔,仅考虑营业时间范围。

Carbon::subOpenTime('2 hours and 30 minutes')      // subtract 2 hours and 30 minutes to now
$carbonDate->subOpenTime('2 hours and 30 minutes') // subtract 2 hours and 30 minutes to $carbonDate

// Can be used with the same interval definitions than add/sub methods of Carbon
$carbonDate->subOpenTime(235, 'seconds')
$carbonDate->subOpenTime(new DateInterval('PT1H23M45S'))
$carbonDate->subOpenTime(CarbonInterval::hours(3)->minutes(20))

$carbonDate->subOpenTime('2 hours and 30 minutes', BusinessTime::HOLIDAYS_ARE_CLOSED)
// subtract 2 hours and 30 minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

subOpenHours

仅考虑时间段的开放区间,减去给定的小时数。

Carbon::subOpenHours(3)      // subtract 3 open hours to now
$carbonDate->subOpenHours(3) // subtract 3 open hours to $carbonDate


$carbonDate->subOpenHours(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// subtract 3 open hours considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

subOpenMinutes

仅考虑时间段的开放区间,减去给定的小时数。

Carbon::subOpenMinutes(3)      // subtract 3 open minutes to now
$carbonDate->subOpenMinutes(3) // subtract 3 open minutes to $carbonDate


$carbonDate->subOpenMinutes(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// subtract 3 open minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

subClosedTime

仅考虑时间段的封闭区间,减去给定的时间间隔。

Carbon::subClosedTime('2 hours and 30 minutes')      // subtract 2 hours and 30 minutes to now
$carbonDate->subClosedTime('2 hours and 30 minutes') // subtract 2 hours and 30 minutes to $carbonDate

// Can be used with the same interval definitions than add/sub methods of Carbon
$carbonDate->subClosedTime(235, 'seconds')
$carbonDate->subClosedTime(new DateInterval('PT1H23M45S'))
$carbonDate->subClosedTime(CarbonInterval::hours(3)->minutes(20))

$carbonDate->subClosedTime('2 hours and 30 minutes', BusinessTime::HOLIDAYS_ARE_CLOSED)
// subtract 2 hours and 30 minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

subClosedHours

仅考虑时间段的封闭区间,减去给定的小时数。

Carbon::subClosedHours(3)      // subtract 3 closed hours to now
$carbonDate->subClosedHours(3) // subtract 3 closed hours to $carbonDate


$carbonDate->subClosedHours(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// subtract 3 closed hours considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

subClosedMinutes

仅考虑时间段的封闭区间,减去给定的小时数。

Carbon::subClosedMinutes(3)      // subtract 3 closed minutes to now
$carbonDate->subClosedMinutes(3) // subtract 3 closed minutes to $carbonDate


$carbonDate->subClosedMinutes(3, BusinessTime::HOLIDAYS_ARE_CLOSED)
// subtract 3 closed minutes considering holidays as closed (equivalent than using 'holidaysAreClosed' => true option)

getCurrentDayOpeningHours

返回当前日期的营业时间设置(首先匹配异常,否则当前工作日的设置)。

BusinessTime::enable(Carbon::class, [
  'monday' => [
    'data' => [
      'remarks' => 'Extra evening on Monday',
    ],
    'hours' => [
        '09:00-12:00',
        '13:00-18:00',
        '19:00-20:00',
    ]
  ],
  // ...
]);

$todayRanges = Carbon::getCurrentDayOpeningHours(); // Equivalent to Carbon::now()->getCurrentDayOpeningHours()
// You can also get opening hours of any other day: Carbon::parse('2018-01-16')->getCurrentDayOpeningHours()

echo '<h1>Today office open hours</h1>';
$data = $todayRanges->getData();
if (is_array($data) && isset($data['remarks'])) {
  echo '<p><em>' . $data['remarks'] . '</em></p>';
}
// $todayRanges is iterable on every time range of the day.
foreach ($todayRanges as $range) {
  // TimeRange object have start, end and data properties but can also be implicitly converted as strings:
  echo '<p><time>' . $range . '</time></p>';
}
// $todayRanges can also be directly dumped as string
echo '<p>' . $todayRanges . '</p>';

在实时编辑器中尝试

isBusinessOpen / isOpenExcludingHolidays

当将 'holidaysAreClosed' 设置为 true 时,等同于 isOpen

允许您知道在给定的时间点企业通常是否营业,而不是节假日。但您也可以使用专用异常处理节假日以实现更精确的设置。请参阅节假日部分

Carbon::setHolidaysRegion('us-national');
Carbon::isBusinessOpen()       // returns true if the business is now open and not an holiday
$carbonDate->isBusinessOpen()  // returns true if the business is open and not an holiday at the current date and time

isBusinessClosed / isClosedIncludingHolidays

当将 'holidaysAreClosed' 设置为 true 时,等同于 isClosed

isOpenExcludingHolidays相反

Carbon::setHolidaysRegion('us-national');
Carbon::isBusinessClosed()       // returns true if the business is now closed or an holiday
$carbonDate->isBusinessClosed()  // returns true if the business is closed or an holiday at the current date and time

nextBusinessOpen / nextOpenExcludingHolidays

当将 'holidaysAreClosed' 设置为 true 时,等同于 nextOpen

转到下一个开放时间(考虑所有节假日为关闭时间)。但建议使用专用异常处理节假日以实现更精确的设置。请参阅节假日部分

Carbon::setHolidaysRegion('us-national');
echo Carbon::nextBusinessOpen();
echo $carbonDate->nextBusinessOpen();

nextBusinessClose / nextCloseIncludingHolidays

当将 'holidaysAreClosed' 设置为 true 时,等同于 nextClose

转到下一个关闭时间(考虑所有节假日为关闭时间)。但建议使用专用异常处理节假日以实现更精确的设置。请参阅节假日部分

Carbon::setHolidaysRegion('us-national');
echo Carbon::nextBusinessClose();
echo $carbonDate->nextBusinessClose();

previousBusinessOpen / previousOpenExcludingHolidays

当将 'holidaysAreClosed' 设置为 true 时,等同于 previousOpen

转到上一个开放时间(考虑所有节假日为关闭时间)。但建议使用专用异常处理节假日以实现更精确的设置。请参阅节假日部分

Carbon::setHolidaysRegion('us-national');
echo Carbon::previousBusinessOpen();
echo $carbonDate->previousBusinessOpen();

previousBusinessClose / previousCloseIncludingHolidays

当将 'holidaysAreClosed' 设置为 true 时,等同于 previousClose

转到上一个关闭时间(考虑所有节假日为关闭时间)。但建议使用专用异常处理节假日以实现更精确的设置。请参阅节假日部分

Carbon::setHolidaysRegion('us-national');
echo Carbon::previousBusinessClose();
echo $carbonDate->previousBusinessClose();

currentOr*

currentOr开头的方法后跟

  • 一个 时间方向Next / Previous
  • 可选的 Business(表示无论'holidaysAreClosed'是true还是false,节假日都自动视为关闭)
  • 一个 状态 Open / Close

所有 currentOr* 方法在当前日期时间处于该 状态(见上文)时返回当前日期时间,否则返回第一个日期时间(根据给定的 时间方向 返回下一个或上一个),该状态变为所选的 状态(开放/关闭)。

注意:BusinessOpen也可以显式地写作OpenExcludingHolidaysBusinessClose作为CloseIncludingHolidays

openOr*

openOr开头的方法后跟

  • 一个 时间方向Next / Previous
  • 可选的 Business(表示无论'holidaysAreClosed'是true还是false,节假日都自动视为关闭)
  • Close(对于open-or-next/previous-open,请参阅currentOr*

所有 openOr* 方法在当前日期时间开放时返回当前日期时间,否则返回第一个日期时间(根据给定的 时间方向 返回下一个或上一个),企业关闭。

注意:BusinessClose也可以显式地写作CloseIncludingHolidays

closedOr*

closedOr开头的函数后面跟

  • 一个 时间方向Next / Previous
  • 可选的 Business(表示无论'holidaysAreClosed'是true还是false,节假日都自动视为关闭)
  • Open(对于closed-or-next/previous-closed,见currentOr*

所有closedOr*方法在关闭时返回当前日期时间,否则返回第一个开放日期时间(根据给定的时间方向,下一个或上一个)。

注意:BusinessOpen也可以显式地写作OpenExcludingHolidays

diffAsBusinessInterval

返回两个日期/时间之间的开放/关闭时间间隔。

$start = '2021-04-05 21:00';
$end = '2021-04-05 10:00:00'; // can be date instance, a string representation or a timestamp
$options = 0;

$interval = Carbon::parse($start)->diffAsBusinessInterval($end, $options);

返回的$intervalCarbonInterval的一个实例。请参阅https://carbon.nesbot.com/docs/#api-interval

选项是管道标志,包括

  • BusinessTime::CLOSED_TIME:对于关闭时间返回间隔,否则返回开放时间
  • BusinessTime::RELATIVE_DIFF:如果开始时间在结束时间之前,返回负值
  • BusinessTime::HOLIDAYS_ARE_CLOSED:自动将假日视为关闭
  • BusinessTime::USE_DAYLIGHT_SAVING_TIME:使用DST本地PHP diff结果而不是真实时间(时间戳)

示例

Carbon::parse($start)->diffAsBusinessInterval($end, BusinessTime::CLOSED_TIME | BusinessTime::HOLIDAYS_ARE_CLOSED | BusinessTime::RELATIVE_DIFF);
// - return relative total closed time between $start and $end
// - considering holidays as closed
// - it will be negative if $start < $end

diffInBusinessUnit

返回两个日期/时间之间给定单位的开放/关闭时间。

Carbon::parse('2021-04-05 10:00')->diffInBusinessUnit('hour', '2021-04-05 21:00:00', $options)

第一个参数是单位单数或复数形式,在任何情况下都一样。其他两个参数与diffAsBusinessInterval中的相同

diffInBusinessHours

返回两个日期/时间之间给定单位的开放/关闭小时数(作为浮点数)。

Carbon::parse('2021-04-05 07:00')->diffInBusinessHours('2021-04-05 10:30', $options)
// return 2.5 if business is open between 8:00 and 12:00

两个参数与diffAsBusinessInterval中的相同

diffInBusinessMinutes

返回两个日期/时间之间给定单位的开放/关闭分钟数(作为浮点数)。

Carbon::parse('2021-04-05 07:00')->diffInBusinessMinutes('2021-04-05 10:30', $options)

两个参数与diffAsBusinessInterval中的相同

diffInBusinessSeconds

返回两个日期/时间之间给定单位的开放/关闭秒数(作为浮点数)。

Carbon::parse('2021-04-05 07:00')->diffInBusinessSeconds('2021-04-05 10:30', $options)

两个参数与diffAsBusinessInterval中的相同

getCurrentOpenTimeRanges

获取包含当前日期时间的范围列表。

foreach (Carbon::getCurrentOpenTimeRanges() as $timeRange) {
  echo 'From: '.$timeRange->start().' to '.$timeRange->end()."\n";
}
foreach ($carbonDate->getCurrentOpenTimeRanges() as $timeRange) {
  echo 'From: '.$timeRange->start().' to '.$timeRange->end()."\n";
}

getCurrentOpenTimeRange

获取包含当前日期时间的第一个范围。

$timeRange = Carbon::getCurrentOpenTimeRange();

if ($timeRange) {
  echo 'From: '.$timeRange->start().' to '.$timeRange->end()."\n";
}

$timeRange = $carbonDate->getCurrentOpenTimeRange();

if ($timeRange) {
  echo 'From: '.$timeRange->start().' to '.$timeRange->end()."\n";
}

getCurrentOpenTimePeriod

获取包含当前日期时间的第一个范围,作为CarbonPeriod

虽然getCurrentOpenTimeRange()返回一个仅处理时间部分的TimeRange实例,但getCurrentOpenTimePeriod()返回一个CarbonPeriod实例,因此您可以获取开始和结束的完整日期和时间。

这主要用于范围跨越午夜的情况

BusinessTime::enable(Carbon::class, [
  'overflow' => true,
  'monday'   => ['22:00-03:00'],
]);

$timeRange = Carbon::getCurrentOpenTimePeriod(); // with current date and time
$timeRange = Carbon::parse('Monday 23:34')->getCurrentOpenTimePeriod();

echo $timeRange->getStartDate()->format('D G\h'); // Mon 22h
echo $timeRange->getEndDate()->format('D G\h'); // Tue 3h

getCurrentOpenTimeRangeStart

获取当前开放时间范围的开始(如果开放,则忽略假日)。

$start = Carbon::getCurrentOpenTimeRangeStart();

if ($start) {
  echo 'Open since '.$start->format('l H:i')."\n";
} else {
  echo "Closed\n";
}

$start = $carbonDate->getCurrentOpenTimeRangeStart();

if ($start) {
  echo 'Open since '.$start->format('l H:i')."\n";
} else {
   echo "Closed\n";
 }

getCurrentOpenTimeRangeEnd

获取当前开放时间范围的结束(如果开放,则忽略假日)。

$end = Carbon::getCurrentOpenTimeRangeEnd();

if ($end) {
  echo 'Will close at '.$start->format('l H:i')."\n";
} else {
  echo "Closed\n";
}

$end = $carbonDate->getCurrentOpenTimeRangeEnd();

if ($end) {
  echo 'Will close at '.$start->format('l H:i')."\n";
} else {
   echo "Closed\n";
 }

getCurrentBusinessTimeRangeStart

获取当前开放时间范围的开始(如果开放且非假日)。

$start = Carbon::getCurrentBusinessTimeRangeStart();

if ($start) {
  echo 'Open since '.$start->format('l H:i')."\n";
} else {
  echo "Closed\n";
}

$start = $carbonDate->getCurrentBusinessTimeRangeStart();

if ($start) {
  echo 'Open since '.$start->format('l H:i')."\n";
} else {
   echo "Closed\n";
 }

getCurrentBusinessTimeRangeEnd

获取当前开放时间范围的结束(如果开放且非假日)。

$end = Carbon::getCurrentBusinessTimeRangeEnd();

if ($end) {
  echo 'Will close at '.$start->format('l H:i')."\n";
} else {
  echo "Closed\n";
}

$end = $carbonDate->getCurrentBusinessTimeRangeEnd();

if ($end) {
  echo 'Will close at '.$start->format('l H:i')."\n";
} else {
   echo "Closed\n";
 }

Laravel

要在Laravel中全局启用business-time,在配置文件config/carbon.php中设置默认开放时间和假日设置(如果尚不存在,则创建此文件)

<?php return [
  'opening-hours' => [
    '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' => [],
      '01-01' => [], // Recurring on each 1st of january
      '12-25' => ['09:00-12:00'], // Recurring on each 25th of december
    ],
  ],
  'holidaysAreClosed' => true,
  'holidays' => [
    'region' => 'us',
    'with' => [
      'boss-birthday' => '09-26',
      'last-monday'   => '= last Monday of October',
    ],
  ],
];

如果您使用Laravel但不想使用此全局配置来启用business-time,您可以使用以下命令将其从自动发现中删除

"extra": {
    "laravel": {
        "dont-discover": [
            "cmixin/business-day",
            "cmixin/business-time"
        ]
    }
},

关于时区的说明

当您设置假日区域时,它不会更改时区,因此如果1月1日是假日,->isHoliday()Carbon::parse('2010-01-01 00:00:00.000000)返回trueCarbon::parse('2010-01-01 23:59:59.999999),无论您为这些Carbon实例设置的时区如何。

如果您想知道世界上其他地方的日期是假日还是工作日,您必须将其转换

Carbon::parse('2010-01-01 02:30', 'Europe/Paris')->setTimezone('America/Toronto')->isHoliday() // false
Carbon::parse('2010-01-01 12:30', 'Europe/Paris')->setTimezone('America/Toronto')->isHoliday() // true

同样的,也适用于营业时间。比如说,你想知道位于多伦多的呼叫中心是否在东京时间的一个特定小时可用,你将得到类似以下的内容:

// Opening hours in Toronto
BusinessTime::enable(Carbon::class, [
  'monday' => ['08:00-20:00'],
  'tuesday' => ['08:00-20:00'],
  'wednesday' => ['08:00-20:00'],
  'thursday' => ['08:00-20:00'],
]);
// Can I call the hotline if it's Tuesday 19:30 in Tokyo? > No
Carbon::parse('2019-03-05 20:30', 'Asia/Tokyo')->setTimezone('America/Toronto')->isOpen() // false
// Can I call the hotline if it's Tuesday 22:30 in Tokyo? > Yes
Carbon::parse('2019-03-05 22:30', 'Asia/Tokyo')->setTimezone('America/Toronto')->isOpen() // true

在实时编辑器中尝试