Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Last active October 27, 2017 16:01
Show Gist options
  • Save sloanlance/c21da41e6cc426a421790490f8c2364c to your computer and use it in GitHub Desktop.
Save sloanlance/c21da41e6cc426a421790490f8c2364c to your computer and use it in GitHub Desktop.
#PHP – A note I added to the PHP manual about timezone constants. http://php.net/manual/en/function.date-default-timezone-set.php#121800
date_default_timezone_set(DateTimeZone::listIdentifiers(DateTimeZone::UTC)[0]);

I avoid using strings as arguments when a constant or other kind of reference should be used. For example, to set the default timezone to UTC, the recommended code is:

<?php
date_default_timezone_set('UTC'); // Potential for mistakes
?>

However, using the string "UTC" here opens up the possibility for mistakes. For example, if the string "UTX" were entered accidentally, most PHP editors PHP won't flag that as an error. When run, the interpreter will show the common warning about a misspelled timezone and using "UTC" by default.

PHP should define constants to represent the major timezones. Actually it does, but DateTimeZone::UTC inconveniently contains the integer value 1024, not a string. However, DateTimeZone::listIdentifiers() can turn a timezone integer into an array of timezone identifier strings. So, I use this code:

<?php
date_default_timezone_set(DateTimeZone::listIdentifiers(DateTimeZone::UTC)[0]); // Foolproof
?>

It's longer, but if I make a mistake specifying the timezone (which I won't because I use code completion), my editor would highlight the problem. If I ran the program with an invalid timezone reference anyway, PHP would give the more helpful error, Fatal error: Undefined class constant 'UTX' in /tmp/tarfu.php on line 24.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment