开发者

get server time in php - timezone issues

开发者 https://www.devze.com 2023-01-13 07:29 出处:网络
on shell, my server time is (simple date in bash): Sun Aug 29 10:37:12 EDT 2010 when I run the code php -r \"echo date(\'Y-m-d H:i:s\');\" I get: 2010-08-29 10:37:10

on shell, my server time is (simple date in bash): Sun Aug 29 10:37:12 EDT 2010

when I run the code php -r "echo date('Y-m-d H:i:s');" I get: 2010-08-29 10:37:10

but when I execute a php script that has echo date('Y开发者_运维问答-m-d H:i:s'); I get a different time- since php thinks the timezone is UTC (server time is EDT).

My php.ini file has no timezone set, and I wouldnt like to change anything- as I have no idea what affect it would have on other sites that run on this server.

Is there a simple way to get the server time- at the timezone that is set for the server?


According to the php.ini directives manual page, the timezone isn't set by default if you're using a version prior to 5.3. Then if you take a look at the page for date_default_timezone_get, it uses the following order for getting the timezone:

* Reading the timezone set using the date_default_timezone_set() function (if any)
* Reading the TZ environment variable (if non empty) (Prior to PHP 5.3.0)
* Reading the value of the date.timezone ini option (if set)
* Querying the host operating system (if supported and allowed by the OS)

UTC is the default if all of those fail, so that's probably a good starting point.


The server should always have a timezone specified in the php.ini file. PHP 5.3 even raises notices if that's not the case and the DateTime extension will throw exceptions if you attempt to build objects without explicitly specifying a timezone (with a DateTimezone object) or having a default one (either through date.timezone or date_default_timezone_set).

By what you're describing, the most likely scenarios are:

  • Different php.ini files are being used in the two scenarios. In the first case, no default timezone is specified, so PHP attempts to infer one from the system-wide timezone of the machine.
  • The (second) script calls date_default_timezone_set('UTC') or equivalent.


Late for the party, but if you want to set the timezone without edit php.ini, you can put in the php code one of these strings:

date_default_timezone_set('GMT');
date_default_timezone_set('Europe/Zurich');
date_default_timezone_set('America/New_York');


Have you tried using date_default_timezone_set() American timezones can be found here http://www.php.net/manual/en/timezones.america.php

0

精彩评论

暂无评论...
验证码 换一张
取 消