【发布时间】:2011-02-19 12:46:48
【问题描述】:
我目前正在使用数据库中的 'time()' 函数存储时间。但是,它使用服务器的时区,我希望每个用户根据他们的时区(在他们的个人资料中设置)查看时间。
如何进行时间戳转换? (我的意思是从时间戳到时间戳,而不是可读时间)
【问题讨论】:
我目前正在使用数据库中的 'time()' 函数存储时间。但是,它使用服务器的时区,我希望每个用户根据他们的时区(在他们的个人资料中设置)查看时间。
如何进行时间戳转换? (我的意思是从时间戳到时间戳,而不是可读时间)
【问题讨论】:
UNIX 时间戳按 UTC 定义,这意味着所有转换都应在打印之前完成,而不是使用实际时间戳。
但是,如何执行此操作取决于您当前如何格式化它们。我相信 PHP 有内置的时区处理。
【讨论】:
正如 Joonas 所说,UNIX 时间戳在定义上是 UTC,但如果您确实需要,您可以将类似的东西组合在一起以模仿特定时区的时间戳:
// PHP 5.3 - OO Code
$timestamp = time();
echo 'Unix timestamp: ' . $timestamp;
$dt = DateTime::createFromFormat('U', $timestamp);
$dt->setTimeZone(new DateTimeZone('America/New_York'));
$adjusted_timestamp = $dt->format('U') + $dt->getOffset();
echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;
// PHP 5.3 - Procedural Code
$timestamp = time();
echo 'Unix timestamp: ' . $timestamp;
$dt = date_create_from_format('U', $timestamp);
date_timezone_set($dt, new DateTimeZone('America/New_York'));
$adjusted_timestamp = date_format($dt, 'U') + date_offset_get($dt);
echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;
【讨论】:
真的,您不应该破解时间戳本身来更改其中的日期,您应该在将格式化的日期戳呈现给用户之前将时区应用于时间戳。
这是 Mike 代码的修改版本,适用于 PHP 5 >= 5.2.0 如php.net
// OO Code
$st = 1170288000 // a timestamp
$dt = new DateTime("@$st");
$dt->setTimeZone(new DateTimeZone('America/New_York'));
$adjusted_timestamp = $dt->format('U') + $dt->getOffset();
echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;
// Procedural Code
$st = 1170288000 // a timestamp
$dt = date_create("@$st");
date_timezone_set($dt, timezone_open('America/New_York'));
$adjusted_timestamp = date_format($dt, 'U') + date_offset_get($dt);
echo ' Timestamp adjusted for America/New_York: ' . $adjusted_timestamp;
【讨论】: