Every timestamp I store on the DB server I store it as TIMESTAMP types, and in UTC;
I have two objectives:
- to show a timestamp formatted according to the current user locale; if he changes languages in its profile, I'd want the format to change also;
- to show the correct time according to the user timezone; So, everything gets saved in UTC, but when the user looks at one of those timestamps, I want him to see a correct date according to location they are in. Right now, I give the option to the user to set its desired timezone on its profile, and I keep it in session upon login.
I saw this page:
which basically uses the PHP DateTime and DateTimeZone to do the conversion, both in format and in target time. But the thing I found odd is that it needs to convert the formats used by CDateFormatter into PHP ones ( function YiitoPHPDateFormat() )
In something related, I found:
Which seems to imply that the CDateFormatter relies on the CApplication timeZone property.
- is the following a valid approach to convert a field from DB (in UTC, TIMESTAMP column type), into the current locale and timezone of the current user?
- Does it allow to retain the functionality I'm seeking, without causing problems somewhere else in the application?
... $formatter = Yii::app()->dateFormatter; $stamp = strtotime($modelStampValue); $oldAppTimeZone = Yii::app()->getTimeZone(); Yii::app()->setTimeZone(Yii::app()->user->timezone); $ret = $formatter->formatDateTime($stamp, 'short'); Yii::app()->setTimeZone($oldAppTimeZone); return $ret; ...
This was a solution I found to avoid mixing both Yii function specifics and DateTime/DateTimeZone from PHP.
What do you think?
Thanks in advance!!