php 47 lines · 7 steps

Scheduling reminders across time zones in PHP

A scheduler class converts between a user's local time and UTC so daily digests fire at the right moment.

Explained by highlit
1<?php
2 
3namespace App\Reminders;
4 
5use DateTimeImmutable;
6use DateTimeZone;
7 
8final class ReminderScheduler
9{
10 public function localToUtc(string $localTime, string $userTimezone): DateTimeImmutable
11 {
12 $local = new DateTimeImmutable($localTime, new DateTimeZone($userTimezone));
13 
14 return $local->setTimezone(new DateTimeZone('UTC'));
15 }
16 
17 public function utcToLocal(DateTimeImmutable $utc, string $userTimezone): DateTimeImmutable
18 {
19 return $utc->setTimezone(new DateTimeZone($userTimezone));
20 }
21 
22 public function scheduleDailyDigest(string $userTimezone, string $sendAt = '08:00'): DateTimeImmutable
23 {
24 $tz = new DateTimeZone($userTimezone);
25 $now = new DateTimeImmutable('now', $tz);
26 $next = $now->modify("today {$sendAt}");
27 
28 if ($next <= $now) {
29 $next = $next->modify('+1 day');
30 }
31 
32 return $next->setTimezone(new DateTimeZone('UTC'));
33 }
34 
35 public function displayForUser(DateTimeImmutable $utc, string $userTimezone): string
36 {
37 $local = $this->utcToLocal($utc, $userTimezone);
38 $offset = $local->format('P');
39 
40 return sprintf(
41 '%s (%s, UTC%s)',
42 $local->format('D, M j \a\t g:i A'),
43 $userTimezone,
44 $offset
45 );
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Store timestamps in UTC and convert to a user's zone only at the boundaries of your system.
  2. 2DateTimeImmutable returns new instances, so every modify or setTimezone call must be reassigned to take effect.
  3. 3Anchoring 'today HH:MM' in the user's own timezone before converting keeps digests aligned to their local clock.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Scheduling reminders across time zones in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code