Apr 26, 2024
4
Level 1
How to work with different timezones in Laravel Scheduling
Hey guys!. So I collect time from userA, eg. 06:30PM and timezone is American/Los_Angeles, and save to my database like below.
try {
$schedules = new Schedule();
$days = json_encode($data['days']);
$timezone = auth()->user()->guardian->timezone;
$time = Carbon::parse($data['time']);
$startDate = $data['startDate'];
$schedules->days = $days;
$parsedTime = $time->setTimezone($timezone);
$schedules->time = $parsedTime->utc();
$schedules->startDate = $startDate;
$schedules->save();
if ($data) {
return $this->saveSubjectSchedule($data['subject'], $data['topic'], $schedules, $data['kid']);
}
return response()->json(['message' => 'Schedule saved successfully', 'success' => true, 'data' => $schedules], 200);
} catch (\Throwable $th) {
return response()->json(['error' => 'Failed to save schedule', 'message' => $th->getMessage(), 'success' => false], 500);
}
And now I want to send email 2 hours before the time the user picked, eg. 06:30PM. This is where I am confused. Do I need to convert to the users timezone before sending the mail, or will the UTC time I saved to DB be enough, since the user picked 06:30PM. COs if I convert to users timezone, it gives me 11:30. Please I really need an explanation and the best way to handle this in Laravel scheduler. Thanks.
This is what I did already for the scheduler -
$adjustedTime = $currentDateTime->addHours(2)->format('H:i'); // Current time plus two hours without seconds
$assignments = TutorAssignment::whereHas('kidSubjectSchedule.schedule', function ($query) use ($currentDateTime, $adjustedTime) {
$query->whereDate('startDate', '<=', $currentDateTime->toDateString())
->whereTime('time', '=', $adjustedTime)
->where(function ($query) use ($currentDateTime) {
$dayOfWeek = $currentDateTime->dayOfWeek;
$query->whereJsonContains('days', [['value' => $dayOfWeek]]);
});
})->with('kidSubjectSchedule')->get();
return $assignments->pluck('id')->toArray();
Please or to participate in this conversation.