PHP and system dates are different

I get different dates / times between the system and PHP.

System

        $ date
        Tue Nov  3 19:16:51 EAT 2015

Php

        echo date("D M j G:i:s T Y");
        -> Tue Nov 3 16:16:23 UTC 2015

It looks like PHP defaults to UTC, although the system has a different time zone. How can I get PHP to choose a system date and time?

Note. I avoid hard timezone coding for maintenance reasons.

Thanks.

+4
source share
3 answers

There doesn't seem to be a simple (system independent) way to get the system date / time in PHP, but this seems to work:

    $timezone = 'UTC';
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         $timezone = exec('tzutil /g');
    } else {
            $timezone = exec('date +%Z');
    }

    $localTimezone = new DateTimeZone($timezone);
    $myDateTime = new DateTime(date(), $localTimezone);
    echo ($myDateTime->format('D M j G:i:s T Y') );

I have not tested on Windows, but it works on Linux.

+1
source

Try this entry at the top of the file.

date_default_timezone_set('Country');

Example:
date_default_timezone_set('Hongkong');

0
source

php.ini, date.timezone :

; ...

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = 'America/Chicago'

; ...

PHP.


script , :

<?php
function setTimezone($OSXPassword = null){

    $timezone = null;
    switch(true){
        //Linux (Tested on Ubuntu 14.04)
        case(file_exists('/etc/timezone')):
            $timezone = file_get_contents('/etc/timezone');
            $timezone = trim($timezone); //Remove an extra newline char.
            break;

        //Windows (Untested) (Thanks @Mugoma J. Okomba!)
        case(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'):
            $timezone = exec('tzutil /g');
            break;

        //OSX (Tested on OSX 10.11 - El Capitan)
        case(file_exists('/usr/sbin/systemsetup')):
            if(!isset($OSXPassword)){
                $OSXPassword = readline('**WARNING your input will appear on screen!**  Password for sudo: ');
            }
            $timezone = exec("echo '" . $OSXPassword ."' | sudo -S systemsetup -gettimezone");
            $timezone = substr($timezone, 11);
            break;
    }

    if(empty($timezone)){
        trigger_error('setTimezone could not determine your timezone', E_USER_ERROR);
    } else {
        date_default_timezone_set($timezone);
    }

    return $timezone;
}

setTimezone();
?>

, OSX .

OSX - systemsetup, . root PHP , - , . OSX, root , script .

0

Source: https://habr.com/ru/post/1614312/


All Articles