Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to get system timezone for macOS and Linux in PHP

Oftentimes you would want to retrieve the user’s timezone to perform a certain task. And how would you retrieve it? One way to do it in PHP is by retrieving the timezone set on the user’s system.

Fetch timezone for Linux

So, for instance, if you want to fetch the timezone for Linux systems, you can write a function like so.

function fetchTimeZoneLinux()
    if (file_exists('/etc/timezone')) {
        return ltrim(exec('cat /etc/timezone', $_, $exitCode));
        // Asia/Kolkata

    return exec('date +%Z', $_, $exitCode);
    // IST

Let’s break it down.

The function would first check if the file /etc/timezone exists which holds the system’s current timezone. If this file exists, then we can use the exec function to return the system’s timezone. In my case, it’s “Asia/Kolkata”.

But if in case, the /etc/timezone is not present on the system, you can use the date +%Z command to retrieve the alphabetic timezone abbreviation. In my case, it returned “IST” which is “Indian Standard Time”.

Fetch timezone for macOS/Darwin

The way of getting the system timezone in macOS is a little different. You would need the following function to fetch the timezone like so.

function fetchTimeZoneDarwin()
    if (file_exists('/etc/localtime')) {
        return ltrim(
                "-f 8,9 : /bin/ls -l /etc/localtime | /usr/bin/cut -d '/' -f 8,9", 
        // Asia/Kolkata

As you can tell, you would be using the /etc/localtime file to get the system’s timezone since it’s holding the timezone information in macOS.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a


👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.