Localized Date Time Casting In Laravel cover image

Localized Date Time Casting In Laravel

Published by James Brooks on June 7, 2020

tips laravel

In my newest side-project, Cronbox, users create a new monitor that is used to track whether a cron is running on time or not.

One of the requirements of this is that the cron schedule is configured to the server's timezone (typically UTC). To prevent confusion, I wanted to display the next run time in the users' local timezone.

Previously, I would have used Moment.js to convert the time on the client-side, i.e. in the browser. With Cronbox I came up with another solution using Laravel's Custom Casts feature.

When registering for the service, users select their local timezone which means I can convert the DateTime ahead of time (poor pun, sorry, not sorry!):

Since each monitor has a timezone also assigned to it, if there is no active user instance, it'll happily fall back to the monitor's local time.

Interested in hearing more from me?
Sign up to my newsletter to hear more from me in the future.