I do not like time zones. They’ve been a fairly regular pain point in my career,
especially early on. There was even a time when I built something and totally
forgot that time zones existed and well, it was a mess.
For the most part, time zones don’t cause me much bother anymore. At this point,
I always store everything in a data store in Coordinated Universal Time, and
then convert things to local time zones as necessary.
One such scenario came up recently for me, on a project that’s written in PHP.
While I do maintain some things that run on PHP, I’d say that my muscle memory
for things like time zone conversion have waned considerably as I’ve spend the
better part of the last decade slinging Node.js professionally.
Of course PHP can handle the job, thanks to the DateTime
and DateTimeZone
classes.
So let’s say you have a date/time string that’s in UTC. You can create a new
DateTimeZone
object for UTC and whatever other time zone you’d like. Using
those, you can create a new DateTime
object, that can then have the time zone
set to the new time zone.
Putting it all together, it looks something like this:
$old_tz = new DateTimeZone('UTC'
$new_tz = new DateTimeZone('America/Chicago'
$old_time = new DateTime('2023-03-19 03:30:00', $old_tz
$old_time->setTimezone($new_tz
$new_time = $old_time->format('Y-m-d H:i:s'
var_dump($new_time // 2023-03-18 22:30:00
Of course, you can adjust the time zone names as you see fit.