I am following the tutorial which say to have this code in the model file:
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
This code works as it inputs something in the created_at and updated_at column but the input is 0000-00-00
and also, how to validate date? At the moment I have this: [[‘created_at’, ‘updated_at’], ‘integer’], but on updates when the 0000-00-00 comes back it causes problems.
Any idea how I can solve this problem? Don’t forget I am very new to Yii.
That’s because you may be storing it in the database not as INTEGER but as a DATETIME or TIMESTAMP field (assuming you are using MYSQL). You need to convert date/time formats for display and saving as per your view and database needs.
Alternatively, you can use my yii2-datecontrol extension, which will allow you to set a separate date format globally for saving to model and separate format for display/view. It allows you to override this for each input when rendering at view level as well.
You were right, the database fields were set to "DATE", I have now set them up as "INT" and get a value, but, the value seems to be showing in a Linux as it shows as "1399621641" in both fields.
Without using extensions(as I would like to understand the things without add ons), is there a way to change the format directly from the above code I posted at the start of the thread please?
Before you display a date on your view (form, grid, etc.) convert the date to a format in which you want to display to users. You can either do it in a controller or a model filter/behavior, or write a global class/function (something similar to below):
Of course, you need to enhance the functions above, if you consider translations, locales, other formats, and the limitations of strtotime (since it supports only timestamps - range 1901 to 2038).