I have a system where I manage multiple students, each with their own timezone, class days, and class times. However, my teachers are in a different timezone. I need to convert each student’s class times to match the teacher’s timezone so that scheduling and communication are synchronized.
For example:
Student A is in "Timezone A" and has a class on Monday at 10:00 AM.
Student B is in "Timezone B" and has a class on Monday at 3:00 PM.
The teacher is in "Timezone C."
I want to convert Student A’s class time to match "Timezone C" (teacher’s timezone), which would be Monday at 2:00 AM. Similarly, Student B’s class time should be converted to Monday at 7:00 AM in "Timezone C."
What’s the best approach to achieve this conversion in PHP? Are there any libraries or methods that can help streamline this process?
Any guidance or code examples would be greatly appreciated.
Thank you!
protected function getDaySchedule($weeklyDaysJson, $targetDay, $targetTimeZone)
{
$schedule = json_decode($weeklyDaysJson);
if (!empty($schedule)) {
foreach ($schedule as $entry) {
if ($entry->day === $targetDay) {
$time = $entry->time;
$duration = $entry->duration;
return "$time - $duration minutes";
}
}
} else {
return '';
}
}
Using Yajra Datatable:
->addColumn('monday', function ($row) {
return $this->getDaySchedule($row->weekly_days, 'monday');
})
[![enter image description here](https://i.stack.imgur.com/YFWDM.png)](https://i.stack.imgur.com/YFWDM.png)
2
Answers
This function accepts the week's JSON schedule, the target day, the student's time zone, and the target teacher's time zone as input. It then searches the schedule for the target day, converts the class start time to the teacher's time zone, and includes the duration. If the desired date cannot be found, it returns an empty string.
I use this to yajra by adding column:
Thank You for your help! keep growing
You should alway store timestamps of each column in UTC.
Of course you need timezone of each user in order to make conversions.
Laravel comes with Carbon. It is a library to manage dates (and timezones also!).
To get de date from database, you should instance carbon like this: