与其摆弄时区,为什么不直接做
ALTER TABLE `your_table`
CHANGE `date_added` `date_added`
TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
这会将您的列从 DATE 列更改为 TIMESTAMP 列 https://stackoverflow.com/questions/12408436/convert-all-colums-in-the-rows-from-date-to-timestamp-mysql,在此过程中将所有日期转换为其各自的 UTC 时间戳。
当插入新行时,它将使用当前时间戳作为值 http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html。时间戳始终采用 UTC,因此您不必更改 MySql 服务器上的时区,也不必在插入新行时提供日期。
如果您不能或不想更改列,您也可以通过选择时间戳
SELECT UNIX_TIMESTAMP('date_added') FROM your_table;
对于你的 TimeAgo,你可以这样做
$now = new DateTime;
$dateAdded = new DateTime("@$yourTimestampFromDb");
$dateAdded->setTimezone($now->getTimezone());
$timeSinceAdded = $dateAdded->diff($now);
当您向 DateTime 提供时间戳时,无论您设置的默认服务器时区如何,它将始终使用 UTC。因此,您必须转换$dateAdded
到默认时区(如上所示)或转换$timeSinceAdded
到 UTC。
要将 dateTime 更改为当前访问用户的时区,您可以
- 需要在您的数据库中包含此信息,例如因为您要求注册用户提供此信息
-
or 您可以在运行时确定它,通常是通过对访问用户的 IP 进行 GeoIP 查找或从用户的浏览器发送日期时间偏移量。 https://stackoverflow.com/search?q=getting%20the%20timezone%20of%20the%20user
无论如何,您只需将两个日期时间更改为该时区即可。这可以通过以下方式轻松完成setTimezone(). https://stackoverflow.com/questions/2095020/how-do-you-change-the-timezone-in-php-for-an-existing-timestamp/2095165#2095165
The $timeSinceAdded
那么将是一个DateInterval
目的,你可以这样使用 http://php.net/manual/en/dateinterval.format.php
echo $timeSinceAdded->format('%a total days');
请参阅链接了解更多详细信息,例如可用的格式修饰符。