Display datetime from db in other format

Hi!

I’d like to display datetime from db in other format. i’ve used method afterFind in my model to convert the datetime format, but when it displayed, all the datetime change to current datetime. how can i get datetime from db after convert them? here is the method:


	protected function afterFind ()

	{

        // convert to display format

        $this->date_commande = strtotime ($this->date_commande);

        $this->date_commande =Yii::app()->dateFormatter->formatDateTime(CDateTimeParser::parse($this->date_commande, 'yyyy-MM-dd', time()),'full');


        return parent::afterFind ();

        }   



Please help!

hi

use get function in your model




function getDate(){

// convert $this->date_commande

return $newDate;

}



in your controller / view :




echo $model->getDate;



I do not recommend to change the format of a field in afterFind or in the model.

Application/company specific formatter:




class YFormatter extends CFormatter {

    public function formatLocalDate($value)

    {

        if (! is_numeric($value)) {

            $value = strtotime($value);

        }

        return Yii::app()->localtime->formatDateTime($value,'short',null);

    }

}

The example above relies on my localtime application component which converts a utc time to a local time (all my database times and internal times are in UTC).




// in config.php:

return array(

 //

 'components'=>array(

    'format'=>array(

        'class'=>'YFormatter',

    ),

);



Then, the CGridView field configuration becomes:





  	array(

          'name'=>'date_commande',

          'type'=>'localdate',

          ),



Which will magically call the formatLocalDate method in the formatter class ;-),

and you can of course call ‘Yii::app()->format->formatLocalDate()’ too where ever you need it.

thank’s for help Friend. I solved it. All the same I post The Code:

model:


	

        function getDateTime(){

	// convert $this->date_commande

	return Yii::app()->dateFormatter->format("dd MMMM yyyy H:mm:s", $this->date_commande);

	}



view:




$model->dateTime



le_top thank you for the recommandation. that’s better structured in my opinion.

okay adding date format to formatter is cool if you using that in more than one grid/place otherwise I would stick with a simple method


public function getFormatedDate()

{

      return Yii::app()->dateFormatter->formatDateTime(CDateTimeParser::parse($this->date_commande, 'yyyy-MM-dd', time()),'full')

}



then in my grid I would have something like


columns=>[

     'formatedDate',

     ...

]

The issue with that is that the filter, sorting, etc does not operate anymore. You end up adding more code to make that work again than you would if you were using a formatter.

Further the formatter can be easily applied to other date fields without having to add a setter (a getter, a sort configuration, …) everywhere you want to format the date differently.

Finally the date format may be just the date in some cases, but date and time in other cases, yet in another case you like it to be without seconds and then you want it as text (e.g.,"on 12/12/2013 at 13:13").

As I wanted to introduce parameters in the type format provided to grid view, my formater has a different implemetation for ‘format’:


    /**

 	* Override the default format function to allow parameters to the formatter.

 	*

 	* (non-PHPdoc)

 	* @see CFormatter::format()

 	*/

    public function format($value,$type)

    {

        $params=null;

        if(is_array($type)) {

            $params=$type;

            $type=$type['type'];

            unset($params['type']);

        }

        $method='format'.$type;

        if(method_exists($this,$method)) {

            if($params===null) {

                return $this->$method($value);

            } else {

                return $this->$method($value,$params);

            }

        } else {

            throw new CException(Yii::t('yii','Unknown type "{type}".',array('{type}'=>$type)));

        }

    }


// Example of different localtime:


    public function formatLocalDatetime($value,$params=array())

    {

        if (! is_numeric($value)) {

            $value = strtotime($value);

        }

        $d='short';$t='short';

        if(count($params)==2) {

            $d=$params[0];

            $t=$params[1];

        }

        return Yii::app()->localtime->formatDateTime($value,$d,$t);

    }

// Implementation for formatting numbers:


    /**

 	* (non-PHPdoc)

 	* @see CFormatter::formatNumber()

 	*/

    public function formatNumber($value, $params=array()) {

        $p=array($this->numberFormat['decimals'],$this->numberFormat['decimalSeparator'],$this->numberFormat['thousandSeparator']);

        $c=0;

        foreach($params as $i) {

            $p[$c]=$i;

        }

        return number_format($value,$p[0],$p[1],$p[2]);

    }



Yes, a bit more complex, but I can write this:




        	array('name'=>'the_date_time',

                	'type'=>array(

                        	'type'=>'localdatetime',

				'long',

				'short',

                    ),




perhaps you did not notice this

I know the filtering won’t work on that unless necessary code added to make it work I myself use Formatter that was just merely a suggestion just to give him another option incase he is not filter/sorting that column

Hi, I did notice ‘is cool’, but felt that the rest of message was hiding this too other users.

I have a guiding principle: whatever you do once, you will do at least two times. Hence there is repetition (in >80% of the cases).

Hence coding as if you are going to repeat is usefull in most of the cases. There are a few rare exceptions where the effort to prepare for repetition is too big, only then not preparing for repetition is justified in my humble opinion.