Search code examples
twitter-bootstrapyiiyii-booster

How to format dates with DatePicker in Yii-Booster?


Background

YiiBooster's Date Picker is a wrapper for a neat little widget (bootstrap-datepicker) which is based on Stefan Petre's bootstrap-datepicker. It is very similar to, but not the same as JQueryUI's DatePicker.

Problem

Date format! All of these widgets take a value and display it both in an input field and a nice graphical calendar. The problem is that the date format we want to display to the end-user is usually not the same as the format used by the underlying database. A database like MySQL will typically store it in something like INT (Unix timestamp) or DATE or DATETIME or TIMESTAMP, while the end-user should see a specific format, depending on localization.

YiiBooster's Date Picker takes the raw value directly from the database and displays it in the input field. This is obviously unacceptable, especially when we are storing the date as a Unix timestamp.

With JQueryUI's DatePicker this is easily resolved by specifying the altFormat and altField options. YiiBooster's widget however does not support these parameters.

Question

What is the best practice for overcoming this issue in Yii? Note that importing JQueryUI's DatePicker is not an option, because it is not visually compatible with Twitter Bootstrap.


Solution

  • What format do you want? Deafult in YiiBooster DatePicker is yyyy-mm-dd hh:mtmt:ss. You can use afterFind function to do that. Here I got you an example:

    protected function afterFind(){
    parent::afterFind();
    
    //this will change format to dd month's name year
    $this->attribute=date('d F, Y',strtotime(str_replace("-", "", $this->attribute)));       
    }
    

    Just put it in your Model. Hope this help. CMIIW