Manoj Dhiman
Manoj Dhiman

Reputation: 5166

Display post time according to timezone name (yii)

I am working on a social app and I want to display time of post according to the user's location timezone. I have used timezone like Asia/Calcutta. Now I want if someone is posting from USA then I should get date according to Asia/Calcutta time zone. in config.php I set

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

And I have a function:

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');
}

In database, date is saving according to the user's location. But when I am displaying that date, it is displaying date as it is in database. Please help

Update Also tried this:

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

Upvotes: 1

Views: 362

Answers (2)

SuReSh
SuReSh

Reputation: 1511

Yii Forum may be help you

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/

also in sql you use CONVERT_TZ function to change datetime according to timezone.

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;

In this sql query i use CONVERT and CONVERT_TZ Convert change the column datatype and CONVERT_TZ change the date time to one timezone to another

    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;

In this sql query i change timezone from -6:00 to +5:30

Upvotes: 0

Alex Blex
Alex Blex

Reputation: 37048

The best approach is to use the same time zone for all datetimes stored in the database, e.g. UTC and convert it to viewer's timezone on render:

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

Upvotes: 1

Related Questions