PHP日期时间比当前时间提前2小时

PHP日期时间比当前时间提前2小时,php,date,datetime,timezone,Php,Date,Datetime,Timezone,我尝试使用以下代码获取当前时间: date_default_timezone_set('America/Chicago'); $curDate = new DateTime(); echo $curDate; 它发出回声的时间比芝加哥时区早两个小时。为什么会这样?我的服务器也设置为芝加哥时区。试试这个(添加日期格式) 1) 正确设置服务器的时区 cd /etc rm -f localtime ln -sf /usr/share/zoneinfo/America/Chicago localtim

我尝试使用以下代码获取当前时间:

date_default_timezone_set('America/Chicago');
$curDate = new DateTime();
echo $curDate;
它发出回声的时间比芝加哥时区早两个小时。为什么会这样?我的服务器也设置为芝加哥时区。

试试这个(添加日期格式)

1) 正确设置服务器的时区

cd /etc
rm -f localtime
ln -sf /usr/share/zoneinfo/America/Chicago localtime
2) 与ntp服务器同步时间:

yum install ntp ntpdate ntp-doc
chkconfig ntpd on
ntpdate pool.ntp.org
/etc/init.d/ntpd start
3) 在php.ini中设置时区

timezone = "America/Chicago"
希望对您有所帮助。

PHP5.2+

$datetime = new \DateTime("now",new \DateTimeZone('UTC'));
$datetime->modify('+2 hour');
^^误解,认为你需要调整2小时,离开是因为它很酷

最佳做法是将日期存储为UTC,或者隐式地存储为Unix历元整数(历元始终为UTC),或者存储为ISO8601,后者在字符串中包含时区。服务器时区不应干扰代码显示正确时间的能力

然后,当您使用存储的日期时

$users_timezone = 'America/Chicago';
$datetime = \DateTime::createFromFormat('U',$epoch_from_server);
$timezone = new \DateTimeZone($users_timezone);
$datetime->setTimezone($timezone);
$datetime = $datetime->format('Y-m-d H:i:s');

这将允许用户在代码提供的用户配置文件中设置时区。另一种选择是使用浏览器报告的时区,但这些时区不可靠。

这很奇怪,你在回显一个对象如果这样做会得到什么:
$curDate=new DateTime(null,new DateTimeZone('America/Chicago');echo$curDate
$curDate=new DateTime()$curDate->setTimezone(新日期时区(“美国/芝加哥”);echo$curDate
?@ghost-DateTime实现了自己的
\uuu-toString()
方法。@johncode哦,好的,谢谢你提供的信息。你能从服务器上的bash shell运行
date
吗?可能时间设置错误如果你有一个对象,我会调用它的一个方法:
$curDate->format(…)
$users_timezone = 'America/Chicago';
$datetime = \DateTime::createFromFormat('U',$epoch_from_server);
$timezone = new \DateTimeZone($users_timezone);
$datetime->setTimezone($timezone);
$datetime = $datetime->format('Y-m-d H:i:s');