如何在时区中使用 Carbon PHP 比较时间

问题描述 投票:0回答:1

我必须找出当前时间是否在特定时区的两个 H:i 之间,我所做的代码是

//Actual time in brisbane 1:10 am Thursday, 28 March 2024 (GMT+10) 
$storeStartTime = Carbon::createFromFormat('H:i', $seller->start_time)->shiftTimezone("Australia/Brisbane"); //2024-03-27T00:00:00+10:00
$storeEndTime = Carbon::createFromFormat('H:i', $seller->end_time)->shiftTimezone("Australia/Brisbane");  //2024-03-27T23:30:00+10:00
$currentTime = Carbon::now()->setTimezone("Australia/Brisbane"); //2024-03-27T14:49:33.482934+00:00
if ($currentTime->between($storeStartTime, $storeEndTime)) {
       //not reaching here although time is between 00:00 and 23:30
       //although its already 28th in brisbane its still showing 27th
}

我怎样才能让它工作?

php laravel php-carbon
1个回答
0
投票

您遇到的问题可能是由于

createFromFormat('H:i', $seller->start_time)
函数不包含日期,这意味着它默认为您服务器时区的当前日期,而不是“澳大利亚/布里斯班”时区的当前日期。另外,由于您没有指定日期,因此您的
$storeEndTime
似乎设置在
$storeStartTime
之前。

这是您的代码的修订版本,可能有效。此版本使用布里斯班时区今天的日期创建开始和结束时间:

// Actual date and time in Brisbane
$currentDateInBrisbane = Carbon::now('Australia/Brisbane');

// Create start and end times using the date in Brisbane
$storeStartTime = Carbon::createFromFormat('Y-m-d H:i', $currentDateInBrisbane->format('Y-m-d') . ' ' . $seller->start_time, 'Australia/Brisbane');
$storeEndTime   = Carbon::createFromFormat('Y-m-d H:i', $currentDateInBrisbane->format('Y-m-d') . ' ' . $seller->end_time, 'Australia/Brisbane');
if ($storeEndTime->lt($storeStartTime)) { // In-case the store closes after midnight
     $storeEndTime->addDay();
}

// Now you checks if the current time in Brisbane is between the start and end times
$currentTime = Carbon::now('Australia/Brisbane');
if ($currentTime->between($storeStartTime, $storeEndTime)) {
    // Do business rules
}

这将根据布里斯班的日期正确生成

$storeStartTime
$storeEndTime
,即使您的服务器位于不同的时区。 这将允许商店在午夜之后继续营业,因为如果
$storeEndTime
早于
$storeStartTime
,我们会在
$storeEndTime
后添加一天。

© www.soinside.com 2019 - 2024. All rights reserved.