PHP:如何将服务器时间戳转换为用户的时区?

时间:2010-05-14 13:09:30

标签: php timezone timestamp

我目前正在数据库中使用'time()'函数存储时间。但是,它使用服务器的时区,我希望每个用户根据他们的时区(在他们的个人资料中设置)查看时间。

如何进行时间戳转换? (我的意思是从时间戳到时间戳,而不是可读时间)

3 个答案:

答案 0 :(得分:9)

正如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;

答案 1 :(得分:2)

你真的不应该自己修改时间戳来改变日期,你应该在将格式化的日期戳给用户之前将时区应用到时间戳。

这是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;

答案 2 :(得分:1)

UNIX时间戳按UTC定义,这意味着所有转换应在打印之前完成,而不是在实际时间戳之前完成。

如何执行此操作取决于您当前如何格式化它们。我相信PHP具有内置的时区处理功能。