开发者

Symfony/Strategy: formatting datetime based on timezone?

开发者 https://www.devze.com 2023-02-24 16:38 出处:网络
In a Symfony application... What is the best way to store user\'s timezone information? Is it found 开发者_JS百科via the culture?

In a Symfony application...

  1. What is the best way to store user's timezone information?

    • Is it found 开发者_JS百科via the culture?
    • What are the standard keys that should be stored? Use PHP timezones and store as text?
  2. How to format server datetimes on the presentation layer?

    • Are there PHP/Symfony helpers to do that?


I use the following strategy:

  • server datetime is UTC
  • all dates are managed and stored in UTC
  • user profile table has a timezone field of type text where is stored his PHP timezone
  • user can set/change their timezone in their profile page (select widget is sfWidgetFormI18nChoiceTimezone)
  • for displaying any date, I use a small helper utcToLocal_date which use the format_date function of the Date helper:

.

function utcToLocal_date($originedatetime, $format = 'g')
{
    if (class_exists('sfContext', false) && sfContext::hasInstance() && sfConfig::get('sf_i18n'))
    {
        $timezone = sfContext::getInstance()->getUser()->getProfile()->getTimezone();
        if (!empty($timezone) && ($newtimezone = new DateTimeZone($timezone)))
        {
            $datetime = new DateTime($originedatetime);
            $datetime->setTimezone($newtimezone);
            $originedatetime = $datetime->format("Y-m-d H:i:s");
        }
    }
    if (function_exists('format_date'))
    {
        return format_date($originedatetime, $format);
    }
    return $originedatetime;
}


On your first question. I don't think a timezone for the user is stored, but of course you could. But you should check the default_timezone setting under .settings in the settings.yml.

For formatting dates you can use the Date helper. Which in turn uses the sfDateFormat class, which is initialized with the current user culture. You can also use this to display the timezone of a given date.

0

精彩评论

暂无评论...
验证码 换一张
取 消