0

How can one get the timezone offset of the physical machine sitting, not the timezone reported by php.ini (and certainly not through geoIP)?

From php.ini or in scripts we can easily set the default timezone. For example, on my box it's

Timezone]

In PHP,

if (date_default_timezone_get()) {
    echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}

if (ini_get('date.timezone')) {
    echo 'date.timezone: ' . ini_get('date.timezone');
}

date_default_timezone_set: Asia/Tokyo
date.timezone: Asia/Tokyo

However, the physical server is sitting in Mountain Time with the access logs having the timezone offset string -0700 in them.


Solved: Using exec() we can get system time and the current timezone offset. This is exactly what was needed. Thanks @codisfy for the inspiration.

echo shell_exec('date +\'%:z\'');

-07:00


Edit: This question (PHP 5.4 Can't Determine Time Zones on its own) is about getting the timezone name, but of importance here is the timezone offset. Thanks for pointing out a possible duplicate, community, alas it is a different requirement.

Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94
  • At the OS level you can select time zone too, or the user level. I don't think there's a reliable way to get the time zone based on physical location, because there's not a reliable way to get location. – TZHX Aug 17 '16 at 16:43
  • Can getting the time from system help you? something like this `print_r(date('Y-m-d H:i:s',(int)(shell_exec('date +%s'))));` – codisfy Aug 17 '16 at 16:50
  • @codisfy Go for it. You saved me time and effort with your idea. Thanks pal. – Drakes Aug 17 '16 at 17:10

1 Answers1

1

From comment to answer: You can get the system time using shell_exec(). With which you can run a command as it would run on a shell and return you the output.

So doing something like this can help:

shell_exec('date +\'%Z\'');

codisfy
  • 2,155
  • 2
  • 22
  • 32
  • This should not be marked as the correct answer. `MST` is not a time zone identifier - it's an abbreviation. Not all abbreviations are going to work as [tz identifiers](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), and [many are ambiguous](https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations). For example, in the case of `MST`, is that `America/Denver` (which uses MST in the winter and MDT in the summer)? or is it `America/Phoenix` (which uses MST year-round)? In the case of CST, that could be China Standard Time... – Matt Johnson-Pint Aug 17 '16 at 17:41
  • @MattJohnson You're right again. I ended up using `shell_exec('date +\'%:z\'');` to return the offset like `-07:00` to use that in log functions, parsed that and adjusted the TZ manually. Thanks for the spot. – Drakes Aug 17 '16 at 18:15
  • That only tells you the *current* offset, which may not be the same for the date in question. Time Zone != Offset. – Matt Johnson-Pint Aug 17 '16 at 22:54