php 计算营业前的小时数?

hlswsv35  于 2023-04-10  发布在  PHP
关注(0)|答案(1)|浏览(132)

我试图计算当前时间与企业重新开业之间的时间跨度(以小时为单位)。
当一个企业已经关闭了一天,我被困在第二天。有没有简单的方法来做到这一点?

$storeSchedule = [
    'Mon' => ['09:00 AM' => '12:00 AM'],
    'Tue' => ['09:00 AM' => '12:00 AM'],
    'Wed' => ['09:00 AM' => '12:00 AM'],
    'Thu' => ['09:00 AM' => '12:00 AM'],
    'Fri' => ['09:00 AM' => '12:00 AM'],
    'Sat' => ['12:00 AM' => '01:00 AM', '09:00 AM' => '12:00 AM']
];

// current (or inputted time)
$timestamp = time();
$status = -1;
$currentTime = (new DateTime())->setTimestamp($timestamp);

foreach ($storeSchedule[date('D', $timestamp)] as $startTime => $endTime) {

    // create time objects from start/end times
    $startTime = DateTime::createFromFormat('h:i A', $startTime);
    $endTime   = DateTime::createFromFormat('h:i A', $endTime);
    
    // Business will open later today
    if ($startTime > $currentTime) {
        $status = round(abs($currentTime - $startTime) / 3600,2);
        break;
    }
    
    // Business is open right now
    if (($startTime < $currentTime) && ($currentTime < $endTime)) {
        $status = 0;
        break;
    }
}

echo $status;
xv8emn3q

xv8emn3q1#

这是一个工作的例子,看看它是否适合你。

<?php

$storeSchedule = [
    'Mon' => ['09:00 AM' => '12:00 PM'],
    'Tue' => ['09:00 AM' => '12:00 PM'],
    'Wed' => ['09:00 AM' => '12:00 PM'],
    'Thu' => ['09:00 AM' => '12:00 PM'],
    'Fri' => ['09:00 AM' => '12:00 PM'],
    'Sat' => ['09:00 AM' => '12:00 PM', '01:00 PM' => '06:00 PM'],
    'Sun' => 'closed'
];

// current (or inputted time)
$timestamp = time();
$status = -1;
$currentTime = (new DateTime())->setTimestamp($timestamp);

$schedule = isset($storeSchedule[date('D', $timestamp)]) ? $storeSchedule[date('D', $timestamp)] : 'closed';

if ($schedule == 'closed') {
    $status = 'Closed for todays';
} else {
    foreach ($schedule as $startTime => $endTime) {
        //Create DateTime objects from start/end times
        $startTime = DateTime::createFromFormat('h:i A', $startTime);
        $endTime   = DateTime::createFromFormat('h:i A', $endTime);

        // Business will open later today
        if ($startTime > $currentTime) {
            $status = round(abs($currentTime->getTimestamp() - $startTime->getTimestamp()) / 3600,2).' hours until opening';
            break;
        }

        // Business is open right now
        if (($startTime <= $currentTime) && ($currentTime <= $endTime)) {
            $status = 'Open now';
            break;
        }

        // Business is closed for today
        if ($currentTime > $endTime) {
            $status = 'Closed for today';
        }
    }
}

echo $status;
?>

相关问题