-
Manual: http://us.php.net/manual/en/function.date-default-timezone-set.php
-
My note: http://php.net/manual/en/function.date-default-timezone-set.php#121800
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
.