Another Round At Time And Dates And Locales


(Thyandrecardoso) #1

Hey, I have an existential doubt about how to deal with timestamps stored in the DB server :)

Every timestamp I store on the DB server I store it as TIMESTAMP types, and in UTC;

I have two objectives:

[list=1]

[*]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.

[/list]

I saw this page:

http://www.yiiframework.com/wiki/197/local-time-zones-and-locales/

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:

http://www.yiiframework.com/forum/index.php/topic/37152-possible-timezone-bug-in-cdateformatter/

Which seems to imply that the CDateFormatter relies on the CApplication timeZone property.

[color="#8B0000"]The Question:[/color]

  • 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!!

André


(Thyandrecardoso) #2

Bump?

Any help appreciated!