简体   繁体   English

Laravel:从 Carbon\\CarbonPeriod 中跳过一些时间范围的时间段

[英]Laravel: Skip time slots from Carbon\CarbonPeriod some time ranges

I'm developing a booking system for a various packages having different durations for each.我正在为各种套餐开发一个预订系统,每个套餐都有不同的持续时间。 The customer should get available time slots from a selected date.客户应该从选定的日期获得可用的时间段。 The date may contain different package bookings with different time intervals.日期可能包含具有不同时间间隔的不同套餐预订。 So, What I'm trying to do is to extract available time slots on the date by skipping all booked time slots.所以,我想要做的是通过跳过所有预订的时间段来提取日期的可用时间段。

Expected output is:预期输出为:

08:00 AM
10:30 AM // 09:00 AM has a booking. and its duration is 1.5 hours
11:30 AM // The current package has 1 hour duration

... until the shop closes for eg 08:00 PM

I'm using CarbonPeriod to get list of time slots.我正在使用 CarbonPeriod 来获取时间段列表。 But, I can't apply the filters to skip all booked time slots.但是,我无法应用过滤器来跳过所有预订的时间段。

$hours = new CarbonPeriod(
    $opening,
    $this->duration() . ' minutes',
    $closing->subMinutes($this->duration())
);

$hours->filter(function ($date) use ($booked) {
    $toSkip = [];
    foreach ($booked as $bookedItem) {
        $bookingTime = Carbon::parse($bookedItem->time);
        $completingTime = Carbon::parse($bookedItem->time)->addMinutes($bookedItem->package->duration());

        if ($date->isBetween($bookingTime, $completingTime)) {
            array_push($toSkip, $date);
        }
    }
    return !in_array($date, $toSkip);
});

Any help would be highly appreciated!任何帮助将不胜感激!

If you don't want to reinvent the wheel, this sounds like a job for spatie/opening-hours or the version dedicated to Carbon: cmixin/business-time如果您不想重新发明轮子,这听起来像是spatie/opening-hours 的工作或专用于 Carbon 的版本: cmixin/business-time

Definition looks like:定义如下:

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'],
]);

Then with CarbonPeriod , use the custom step:然后使用CarbonPeriod ,使用自定义步骤:

$period = CarbonPeriod::create(
    $opening,
    static fn ($date) => $date->nextOpen(),
    $closing,
);

foreach ($period as $slot) {
  echo "$slot\n";
}

You also can easily convert AM/PM string to h0-23 format with:您还可以轻松地将 AM/PM 字符串转换为 h0-23 格式:

Carbon::parse('11:20 PM')->format('H:i')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM