How to Adjust Server time in PHP

September 21, 2019

by Yunus Shaikh

As per your timezone, you can adjust server time using PHP built-in functions.

    $today = date('Y-m-d-G');
    $today = strftime("%Y-%m-%d-%H", strtotime("$today -5 hour"));

There are many answers, however, there is not even one correct at the time of writing. PHP time() function doesn't return the system time, like most folks believe, but it return the PHP localtime, normally set with date.timezone in php.ini, or set with date_default_timezone_set() within a script. For instance in one of my servers, PHP time was set to Europe/Romeand system time to UTC. I had a difference of one hour between system time and PHP time. I'm going to give you a solution that works for Linux, I don't know for Windows. In Linux the system timezone is set in /etc/timezone. Now, this is normally outside my allowed open_basedir setting, but you can add :/etc/timezone to your list to be able to read the file. Then, on top of the scripts, that want to get the system time, you can call a library function that sets the script timezone to the system timezone. I suppose that this function is part of a class, so I use static:

        static function setSystemTz() {
            $systemTz = trim(file_get_contents("/etc/timezone"));
            if ($systemTz == 'Etc/UTC') $systemTz = 'UTC';

To make the matter worse in PHP 5.3.3 'Etc/UTC' is not recognized, while 'UTC' is, so I had to add an if to fix that.

Featured Posts