threelyons's avatar

How to manage scheduled tasks based on the user's timezone?

I have an application which performs specific scheduled tasks for different users. They have a UI which allows them to set the start date/time for the task to begin. but the users are based in multiple time zones, so what is the best way to manage this?

  1. Do I store the start datetime in the DB when they set it, and at the same time store the start datetime for the server's time zone. So essentially the task has the start time saved in two fields. One for the user to see the exact datetime in their local time zone, and another field converted to the server's timezone which I can use to run the scheduler off.

  2. Or, just save the datetime in their local timezone, and convert it into the server's timezone every time the scheduler checks the time?

I assume the first option is better as its only performing the timezone conversion once.

But the next question is how exactly can I perform the timezone conversion. I tried using Carbon setTimezone and saved the two datetimes in my DB, but when I checked, they are both the exact same time. I assumed there would be several hours difference in the records saved.

This is what I have done.

Any help will be greatly appreciated.

Thanks in advance.

   $priceEditJob->discount_start = $request->input('discount_start');

   $discount_server_start = Carbon::createFromFormat('Y-m-d H:i:s', $request->input('discount_start'));

   $priceEditJob->discount_server_start = $discount_server_start->setTimezone('Europe/London');
0 likes
2 replies
hupp's avatar
hupp
Best Answer
Level 11

@threelyons In this case you can do one thing from my point of view you have to set set timezone into config/app.php to UTC and also store datetime in UTC TIme in DATABASE.

Now when you want to display to update you have to convert user entered time to UTC time and save in database. So Database has always UTC Time stored and you can run your cron on database UTC time. when retrived and update use the Accessors & Mutators for virtual changes (not require to store) More Info : https://laravel.com/docs/10.x/eloquent-mutators#accessors-and-mutators

use Carbon\Carbon;

// Assuming you have a Carbon datetime object with the UTC+0530 timezone
$utcOffset0530 = '2023-07-25 12:34:56';
$carbonDatetime = Carbon::parse($utcOffset0530, 'UTC+0530');

// Convert to UTC timezone
$utcDatetime = $carbonDatetime->tz('UTC')->utc();

// Output the result in the desired format
echo $utcDatetime->toDateTimeString(); // Output: 2023-07-25 07:04:56

Let me know your feedback

Please or to participate in this conversation.