使用PHP警告DateTime

Dai*_*ail 3 php datetime date

我有这个代码:

try{
  $datetime1 = new DateTime("now");
  $datetime2 = new DateTime("now");
  $interval = $datetime1->diff($datetime2);
  var_dump($interval);
}
catch(Exception $e) {
  echo $e->getMessage();
}     
Run Code Online (Sandbox Code Playgroud)

我没有看到任何结果var_dump,php的输出是:

DateTime::__construct(): It is not safe to rely on the system's timezone setting
s. You are *required* to use the date.timezone setting or the date_default_timez
one_set() function. In case you used any of those methods and you are still gett
ing this warning, you most likely misspelled the timezone identifier. We selecte
d 'Europe/Paris' for '1.0/no DST' instead
Run Code Online (Sandbox Code Playgroud)

我正在使用php_cli 5.3.8

我能做什么?谢谢

min*_*gos 12

在PHP5.3中,有必要设置时区.

打开php.ini并找到设置date.timezone.取消注释并将其设置为某个值,例如

date.timezone = "Europe/Paris"
Run Code Online (Sandbox Code Playgroud)

然后重启服务器.它应该照顾警告.

[编辑]

@greut提出的解决方案也同样有效.两者之间的区别在于php.ini设置是服务器范围的(将应用于现在和将来在服务器上运行的所有应用程序),同时date_default_timezone_set()应用于当前仅执行的应用程序.

php.ini解决方案让您忘记运行的任何其他站点上的警告 - 但您需要访问php.ini.使用date_default_timezone_set()将覆盖php.ini中的设置,因此如果您愿意,可以同时使用这两种方法.


gre*_*eut 11

在您的代码中执行此操作:

date_default_timezone_set('Europe/Paris');

或者在php.ini中.

但更好的是,阅读文档:http://php.net/date_default_timezone_set