1

I have a MySQL database with date field in format like "2013-04-05".

I also have CActiveForm with a text input which accepts values like "05/10/2013".

What is the proper way to convert between these formats when loading and when submitting the form? Which method do I need to override?

2 Answers 2

4

A common problem, a lot of solutions, here is a simple one :

Use a virtual attribute, e.g. in your model :

public $dateIncomeFormat = 'yyyy-MM-dd';
public $dateOutcomeFormat = 'dd/MM/yyyy';

// get date (FR means french)
public function getDateFR()
{
    return Yii::app()->dateFormatter->format($this->dateOutcomeFormat, CDateTimeParser::parse($this->date, $this->dateIncomeFormat));
}

// set dateFR
public function setDateFR($date)
{
    $this->date = Yii::app()->dateFormatter->format($this->dateIncomeFormat, CDateTimeParser::parse($date, $this->dateOutcomeFormat));
}

You should then :

  • declare dateFR in your model's rules,
  • and use dateFR in your forms instead of date.

You should also read this :

Sign up to request clarification or add additional context in comments.

Comments

0

if date 2013-04-05 has format yyyy-mm-dd and 05/10/2013 has format dd-mm-yyyy you can use:

2013-04-05 => 05/10/2013

$date = implode('/', array_reverse(explode('-', '2013-04-05')));

05/10/2013 => 2013-04-05

$date = implode('-', array_reverse(explode('/', '05/10/2013')));

If you have other date format - here is more flexible functions

// if $date = '05/10/2013' (mm-dd-yyyy) e.g.
function dateToMysql($date, $format = 'd-m-Y') {
    $date = explode('/',$date);
    return date($format, strtotime($date[1]."-".$date[0]."-".$date[2]));
}

// if $date = '2013-04-05' (yyyy-mm-dd) e.g.
function mysqlToDate($date, $format = 'm/d/Y') {
    $date = explode('-',$date);
    return date($format, strtotime($date[0]."-".$date[1]."-".$date[2]));
}

2 Comments

I've asked in which method to do the conversion, not how to use explode() (what I already know)
why do not use it in controller method where you validate your form or in model beforeSave()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.