How to handle daylight savings time in PHP

If you’ve ever dealt with time in PHP you’ve probably been burnt by daylight
savings time before (quite possibly yesterday ;). I’ve been there, waking up on
the Sunday of the time change with an email about timestamps being an hour off or some other anomaly that ends up being related to the time change.

PHP does provide a way to check if a time is in daylight savings time or not,
it’s as simple as using a capital i as the format:

if (date('I', time())) {
    echo 'We are in DST!'
} else {
    echo 'We are not in DST!'
}
PHP

Once you know if you’re in daylight savings time, you can adjust your logic flow
accordingly.

Now this is great when you’re attempting to address some hardcoded issue in your code, but it’s not all that ideal in my opinion. These days I opt to store any
and all timestamps in GMT or UTC and avoid daylight savings time all together.
Doing this presents it’s own set of challenges and adds some complexity to your coding.

First, you’ll want to make sure you’re working with the correct time. One method would be to set the timezone in PHP to either GMT or UTC in php.ini or by using date_default_timezone_set(). The other approach would be to using gmdate() in place of date(). Same arguments, a few hours difference in the results.

Once you’re ensuring that you don’t have regional time being stored, you will
need to address how your users are seeing the date. One trick of mine is to only show relative time, like “1 hour ago” instead of the actual time. By doing this, I can completely avoid converting the time, definitely the path of least
resistance.

If you don’t opt for relative time, you will have a bit more work ahead of you to ensure you’re displaying the correct time for your users. First, you’ll need to make the decision as to whether you will show them time in their timezone or if you’ll pick a single timezone (let’s say Pacific time like Google).

Regardless of what you pick, you will need to force the use of timezone. As
previously mentioned you can do so by setting the timezone in php.ini (if you
decide to use a single timezone) or use date_default_timezone_set() before you call date() to set it to the user’s timezone:

date_default_timezone_set('US/Pacific');
echo date('r', $utc_timestamp);
PHP

There’s a few different approaches discussed here, as mentioned my personal
favorite method is to store everything in GMT and then display the user with
relative times.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.