2012-08-01 181 views
0

我知道有几种方法可以做到这一点,并且它们中的很多都使用DateTime类对象。在时区之间转换

date_default_timezone_set("America/Phoenix"); 
$time=time(); 
$timezone='America/Chicago'; 
//$time and $timezone are then stored accordingly. 

然后我可以在我的时区获取时间::我使用的存储时间戳在数据库

date_default_timezone_set("America/Phoenix"); 
echo date("m/d/Y g:i:s a",$time); 
//or if I want to display it to the user: 
date_default_timezone_set($timezone); 
echo date("m/d/Y g:i:s a",$time); 

我的问题是,是否适当操纵PHP的时区是这样实现的意义当涉及到显示日期和时间的地方,或者我应该使用其中一个打包对象来处理?

+0

如何开始使用[DateTime](http://php.net/datetime)? – zerkms 2012-08-01 20:26:59

+0

但是为什么?我应该有理由吗? – 2012-08-01 20:27:30

+0

主要是因为它为你处理所有这些,所以你不必担心它。 – KRyan 2012-08-01 20:28:09

回答

0

我会推荐使用内置的DateTime对象系列的php来处理这个问题。你可以这样做时区转换与它很容易:

// assuming the data coming from the database and it's in the America/Phoenix timezone 
$localtime = DateTime::createFromFormat('Y-m-d H:i:s', $db_date_string, new DateTimeZone('America/Phoenix')); 
$chicago_time = $localtime; 
$chicago_time->setTimeZone(new DateTimeZone('America/Chicago')); 
print $chicago_time->format('m/d/Y g:i:s a'); 

这使时区的操作在狭小范围内的可能(一个日期时间只)。

此外,我会建议将数据库数据存储在一个时区,并在显示/使用前将其转换为应用程序。这可以为您节省大量的调试时间。 (它可以节省我至少:-P)