Dealing with and formatting dates on Yii

Last updated:


You should always define attributes like create_date and possibly last_update for all your database columns. They're very useful for logging and for extracting metrics from your database and sooner or later you'll need them so you might as well start off with them.

Recommended mysql DATETIME format

if field create_date is of type DATETIME on a db, you can do this

$model = new MyModel();
// mysql-friendly format
$model->create_date = date('Y-m-d H:i:s');  

Configure a CGridView column to display formatted dates


             'value'=>'date_format(new DateTime($data->create_date),"d/m/Y")',
//..more columns

Displaying formatted dates in a CDetailView widget

    // this is just an example format constant. You can use regular formats as well.
    'value'=>date_format(new DateTime($model->create_date),DATE_RFC850)

Setting a default value in a form model for a DATETIME attribute

say you have a 'creation_date' attribute for which you want to set a default value of today's date and time: edit the rules() method in your model:

public function rules()
    return [
        ['date_created','default','value'=>date('Y-m-d H:i:s')], // mysql format

Comparing dates

From my experience, the easiest and most accurate way to compare dates (for example, to see how far apart they are) is to create a DateTime object (with any date string) and then call getTimestamp(), and subtract the timestamps:

// when no string is given, it defaults to the current datetime (now).
$date1 = (new DateTime)->getTimestamp();
$date2 = (new DateTime("2014-09-28 20:17:05"))->getTimestamp();

//this is possible because timestamps are just numbers
$difference = ($date1 - $date2);

if($difference > 0)
    echo "date1 is larger (more recent)";
elseif($difference < 0)
    echo "date2 is larger";
    echo "both dates represent the same time (down to seconds)";


Dialogue & Discussion