Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In OS X: getting the timezone in PHP or from a command prompt in Terminal

Tags:

timezone

php

For some reason, the PHP developers decided a while ago that they don't want to trust the timezone information available from the system. So your PHP script under OSX, if it is going to use any time/date function, must do something like:

date_default_timezone_set ("Europe/London");

Now, I don't know where on the planet my script is going to be executed, and it's unreasonable to expect an ordinary user to have to supply a timezone string - the user is going to say, quite reasonably, that they've already set that in the System prefs so why can't I look for it there.

So, up to now, I've been doing:

$cmd = '/usr/sbin/systemsetup -gettimezone';
exec ($cmd, $results, $result);

and picking through the results to get a string to use. So far so good. Now I observe two things:

  1. The man page for this command insists I need "at least admin priv to run". I tried it on an account without admin priv and this is indeed the case, so long term I'll need another approach.

  2. I happened to lock the TimeZone Pane in the System Preferences -> Date&Time, and observed repeatably that whenever this pane is locked, the systemsetup command I gave above pauses for exactly 30 secs before responding. If I unlock the TimeZone pane, it responds in the usual short time.

Does anyone know why this is happening?

Secondly, is anyone aware of an alternative command I can exec to give me the timezone, which doesn't need admin priv?

Thanks,

like image 844
user1164763 Avatar asked Nov 05 '12 18:11

user1164763


2 Answers

OS X stores the system's time zone by making a symbolic link from /etc/localtime to the correct time zone file under /usr/share/zoneinfo/. See "man 3 tzset".

Since you're already in PHP, you could do this to get the time zone's name:

$systemZoneName = readlink('/etc/localtime');
$systemZoneName = substr($systemZoneName, strlen ('/usr/share/zoneinfo/'));

Then, to make that the default time zone you could do this:

date_default_timezone_set ($systemZoneName);

You should also be able to do

ini_set('date.timezone', $systemZoneName);

or, if you just need a DateTimeZone object,

$systemZone = new DateTimeZone ($systemZoneName);
like image 147
jtcours Avatar answered Nov 07 '22 11:11

jtcours


for PHP script under OSX

<?php
$systemtimezone = exec('/bin/ls -l /etc/localtime|/usr/bin/cut -d"/" -f7,8');
date_default_timezone_set($systemtimezone); 
?>

This is how got PHP to read the OS X system default timezone

ps: the pipe in the EXEC may not be a good idea if it gets disallowed in future updates, you may need to cut the string in PHP code instead.

like image 35
Michael N Avatar answered Nov 07 '22 12:11

Michael N