2016-01-06 37 views
1

我正在開發一個社交應用,我想根據用戶的位置時區顯示帖子的時間。我使用的時區類似亞洲/加爾各答。現在我想如果有人從美國發帖,那麼我應該根據Asia/Calcutta時區獲得日期。 在config.php我設置根據時區名稱顯示發帖時間(yii)

$timzone=isset($_COOKIE['goalsurf_timezone'])? $_COOKIE['goalsurf_timezone'] : 'America/Los_Angeles'; 
date_default_timezone_set($timzone); 

而且我有一個函數:

function gplustime($date) 
{ 
    $time=strtotime($date); 
    $dt = new DateTime("now", new DateTimeZone($this->timezon)); //first argument "must" be a string 
    $dt->setTimestamp($time); //adjust the object to correct timestamp 
    return $dt->format(yii::app()->params['dateformat'].' h:i A'); 
} 

在數據庫中,日期是根據用戶的位置進行保存。但是,當我顯示該日期時,它顯示日期,因爲它在數據庫中。請幫助

更新 也試過這樣:

function gplustime($date) 
{ 
    $date = new DateTime($date, new DateTimeZone($this->timezon)); 
    return $date->format(yii::app()->params['dateformat'].' h:i A'); 
} 

回答

1

最好的方法是使用存儲在數據庫中,例如所有的日期時間相同的時區UTC並將其轉換爲觀衆的時區上渲染:

$dt = new \DateTime($dateFromTheDB, new \DateTimeZone('UTC')); 
$dt->setTimeZone(new \DateTimeZone($viewerTimeZone)); 
return $dt->format(yii::app()->params['dateformat'].' h:i A'); 
0

的Yii論壇可幫助您

http://www.yiiframework.com/forum/index.php/topic/63546-sql-serverimplicit-conversion-from-data-type-varchar-to-varbinarymax-is-not-allowed-use-the-convert-function-to-run-this-query/

也在SQL使用CONVERT_TZ功能可以根據時區改變日期時間。

SELECT `groupId`, CONVERT(`name`, CHAR(255)) as `name`, `image`, `type`, `status`, CONVERT_TZ(`addedDate`,'-6:00','".$zone."') as `addedDate` FROM `msg_user_group` WHERE `groupId` = 1; 

在該SQL查詢我使用CONVERT和CONVERT_TZ 轉換改變的列數據類型和CONVERT_TZ更改日期時間給一個時區到另一個

CONVERT_TZ(`addedDate`,'-6:00','".$zone."') 
'addedDate' => field name 
'-6:30' => my current time zone 
'$zone' => here put your timezone in which datetime format is change 


SELECT `groupId`, CONVERT(`name`, CHAR(255)) as `name`, `image`, `type`, `status`, CONVERT_TZ(`addedDate`,'-6:00','+5:30') as `addedDate` FROM `msg_user_group` WHERE `groupId` = 1; 

在該SQL查詢我改變時區從-6 :00至+5:30

+1

不需要這樣做。只需將您的默認日期設置爲PST並使用此http://codingbin.com/display-local-time-according-to-visitors-location-with-javascript-and-php/ – MKD