【问题标题】:Timezone is correct but Time is not - PHP MySQL时区正确但时间不正确 - PHP MySQL
【发布时间】:2013-07-21 18:43:06
【问题描述】:

我正在制作一个小 twitter 克隆只是为了学习,我遇到了一个问题,在 允许用户选择他们所在的时区之前,显示他们何时发推文的时间某些事情是错误的。

这是我的代码的 sn-ps:

/* current date/time whenever they send a tweet */

    $time = date('Y-m-d H:i:s');

/* Insert into db as `time` */


/* Time retrieved as $value['time'] & users timezone as $_SESSION['timezone'] */
/* Convert to users timezone */

    $users_timezone = new DateTimeZone($_SESSION['timezone']);
    $date = new DateTime($value['time']);
    $date->setTimeZone($users_timezone);
    $new_date = $date->format('M j, o g:i a e');
    echo $new_date;

洛杉矶地区目前是上午 11:32,但转换后显示为下午 6:26

我的默认设置是在柏林,目前是晚上 8:33,但在转换之前它显示的是凌晨 1 点

谁能告诉我这方面的见解?第一次这样做。

【问题讨论】:

  • $_SESSION['timezone'] 的值是多少?此外,您实际上并没有将时间作为VARCHAR 存储到数据库中吗?您可能应该将其存储为 DATETIME,并且应该使用 UTC。

标签: php mysql date datetime timezone


【解决方案1】:

检查系统时间

请通过 ssh 运行 date 检查您服务器的当前系统时间。

我相信 php 从系统中获取日期,因此如果您的系统时间不正确,那么您的 php 时间也将不正确。

查看$value['time']

您正在使用 DataTime 类中的构造方法。这是该方法的文档。

http://www.php.net/manual/en/datetime.construct.php

确保$value['time'] 采用可接受的格式。轻松做到这一点的方法是使用strtotime 函数。这将从 $value['time'] 生成一个 unix 时间戳,这可能会满足 DateTime 类的构造方法。

【讨论】:

  • 刚刚做了,它正在显示正确的时间。还是不知道怎么回事!
  • 你能echo $value['time']吗?然后尝试将这一行 $date = new DateTime($value['time']); 更改为 $date = new DateTime(strtotime($value['time']));
猜你喜欢
  • 2014-04-12
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 2015-09-13
  • 2018-06-07
  • 2014-06-29
相关资源
最近更新 更多