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?
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$storeEndTimeis set before the$storeStartTimesince 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:
This will correctly generate the
$storeStartTimeand$storeEndTimeaccording 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$storeEndTimefalls before$storeStartTime, we add a day to$storeEndTime.