title: Automagically detecting timezone from reliable system sources
body: <p>I'm writing a CLI PHP script, and I want the log messages it'll display to contain the correct local time.</p>
  
  <p>This script will be being included in a small software release and run on different machines (on Linux) as part of a configuration step. I only need the time to correctly timestamp log messages, none of the other parts of the system need current-time information, and my use of PHP is an implementation detail, so I feel it would be unreasonable to require users (who may be installing PHP just to run this) to edit the script or fiddle with their PHP installation to set <code>date.timezone</code>.</p>
  
  <p>I say the above in light of the fact that...</p>
  
  <ul>
  <li><code>python -c 'import datetime; print datetime.datetime.now()'</code></li>
  <li><code>ruby -e 'print Time.now, "\n"'</code></li>
  <li><code>perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'</code></li>
  <li><code>awk 'BEGIN { print strftime("%F %T", systime()) }'</code></li>
  <li><code>date</code></li>
  </ul>
  
  <p>...are all properly cognizant of the fact that it's not <em>quite</em> 4AM, but has in fact just gone half past three in the afternoon instead.</p>
  
  <p>Initially Node.js seemed to be in the same stubborn-UTC camp, but it seems there are libraries that are able to autodetect the current timezone and apply it. I'm not aware of anything similar for PHP.</p>
  
  <p>And unfortunately, according to <a href="https://bojanz.wordpress.com/2014/03/11/detecting-the-system-timezone-php/" rel="nofollow noreferrer">https://bojanz.wordpress.com/2014/03/11/detecting-the-system-timezone-php/</a>, PHP stopped looking at the system's idea of the timezone in version 5.4, back in 2012.</p>
  
  <p>I don't fully understand why PHP decided to just throw in the towel and resort to "user-hardcoded or bust" when 4 other major programming languages I just tested worked fine.</p>
  
  <p>That being said, I trust there's a valid reason, and I would very much like to read about it.</p>
  
  <p>On my (Slackware) system TZ is unset, but <code>/etc/localtime</code> is a copy of my timezone file. Note that it's <strong>not</strong> a symlink, so the <code>readlink()</code> workaround noted in the above link is irrelevant for me.</p>
  
  <p>I've repeatedly wondered how complex it would be to actually open and parse my localtime file.</p>
  
  <p>The DateTime and various date functions provide no way to parse arbitrary tzinfo files.</p>
  
  <p><code>strace</code>ing PHP shows that it opens and reads <code>/etc/localtime</code> as it starts up, but depressingly the language doesn't expose the loaded data in any way.</p>
  
  <p>I wasn't able to find any duplicates of this question, but I'll be <em>very</em> surprised if there are none since this has been an arguably open issue for just under 6 years at time of writing this.</p>