Format the datetime value in Yii 2

Format the datetime value in Yii 2

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Formatting Datetime Values in Yii 2

When working with timestamps stored in a database, you often encounter raw strings like 2014-06-30 02:52:51.210201. While this format is machine-readable and ideal for sorting or querying, displaying it directly to a user is rarely intuitive. The goal is frequently to transform this into a localized, human-friendly string like 30-06-2014 02:52:51.

Yii 2 provides robust mechanisms to handle this transformation without manual parsing in every view or controller action. The framework encourages a separation of concerns: data storage remains raw, while presentation logic is handled by formatters. This approach ensures consistency across your application regardless of where the data is rendered.

Global Formatter Configuration

The most effective way to enforce a specific datetime format globally is through the configuration file. By defining a yii\i18n\Formatter component in your application config, you set default rules that apply to the entire runtime environment.

In your config/web.php (or equivalent), you can add the following section:

'components' => [
    'formatter' => [
        'class' => 'yii\i18n\Formatter',
        'dateFormat' => 'd-M-Y',
        'datetimeFormat' => 'd-M-Y H:i:s',
        'timeFormat' => 'H:i:s',
    ],
],

Once configured, this component becomes the single source of truth for date formatting. You can then render dates anywhere in your application using the Yii::$app->formatter instance or via the helper method \Yii::$app->formatter->asDatetime(). For example:

echo \Yii::$app->formatter->asDatetime($model->created_at);

This configuration ensures that even if a view forgets to format a date manually, the framework handles it automatically based on the locale and settings defined here.

Custom Attributes with Accessors

Sometimes the global configuration isn't enough, or you need a specific format that differs from the default locale settings. In such cases, defining a custom getter in your model is a clean solution. This encapsulates the formatting logic within the data layer itself.

To handle microseconds (which are common in MySQL DATETIME fields) and strip them for display, you can use the following pattern:

public function getFormattedCreateTime()
{
    // Create DateTime from raw string, handling microseconds if present
    $date = \DateTime::createFromFormat('Y-m-d H:i:s.u', $this->create_time);
    
    // Format without microseconds for display
    return $date->format('d-m-Y H:i:s');
}

This method returns a clean string that can be echoed directly in your views: echo $model->formattedCreateTime;.

Integrating with GridView Search

A common pitfall when using custom attributes is ensuring they work seamlessly with data grids, specifically the search component. If you define a getter like getFormattedCreateTime, you might wonder if Yii's GridView will automatically use it for filtering or sorting. By default, the active record layer looks for properties that match column names in the database. Since your custom getter returns a calculated string rather than a database value, standard search filters won't work out of the box on that specific attribute.

To enable searching or sorting based on this formatted view, you need to explicitly map it in your activeSearch class. You can do this by overriding the search() method and adding the custom attribute as a searchable field:

public function search($params)
{
    $model = new MyModel();
    $query = \Yii::$app->db->createCommand('SELECT * FROM my_table WHERE ...'); // Mock query
    
    // Add the custom attribute to the model's attributes for search
    $this->addSearchFields($model, [
        'formattedCreateTime' => [
            'attribute' => 'create_time', // Map back to DB column if needed for sorting
            'filterType' => \yii\web\View::INPUT_TEXT,
        ],
    ]);
}

Alternatively, if your goal is simply to display the formatted time in the grid without filtering on it, you must ensure the GridView displays the property name correctly. If the column header shows formattedCreateTime but the cell renders raw data, you may need to adjust the dataProvider or use a custom column renderer that calls the getter explicitly.

Trade-offs and Considerations

While global formatters offer convenience, they come with a trade-off: rigidity. Once set globally, changing the format requires touching the config file or restarting the application server. Custom getters offer flexibility per model but can lead to code duplication if you have many models requiring different date formats.

If your project spans multiple languages and regions, relying solely on hard-coded d-m-Y formats might break internationalization efforts. The global formatter approach respects the user's locale settings (e.g., using M/D/Y for US users), whereas a custom getter with a fixed format string overrides this behavior unless you dynamically pass the locale to the format() method.

For complex applications where date handling is critical, consider whether the need for a specific display format justifies adding complexity to the model layer. Often, sticking to the global formatter and letting the view layer handle exceptions is the more maintainable path.

Our network