How can i compare time using Carbon PHP in a timezone

43 views Asked by At

I need to determine if the current time falls between two 'H:i' times in a specific timezone. Here is the code I have written:

// The actual time in Brisbane is 1:10 am on 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)) {
    // The code is not reaching here even though the time is between 00:00 and 23:30
    // Even though it's already the 28th in Brisbane, it's still showing the 27th
}

How can I make this work?

1

There are 1 answers

0
Malvin Lok On

The issue you encounter may be due to the fact that the createFromFormat('H:i', $seller->start_time) function does not include a date, which means that it defaults to the current date in your server's time zone, not in the "Australia/Brisbane" time zone. Also, it seems that your $storeEndTime is set before the $storeStartTime since you are not specifying a date.

Here is a revised version of your code that might work. This version creates the start and end times using today's date in the Brisbane time zone:

// 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
}

This will correctly generate the $storeStartTime and $storeEndTime according to the date in Brisbane, even if your server is in a different timezone. And it will allow the store to remain open past midnight, because if $storeEndTime falls before $storeStartTime, we add a day to $storeEndTime.