I have configured a date field appointment_date as datetime
field in mysql db.
In my model Appointment.php rules are set like this:
public function rules()
{
return [
[['appointment_date','weekdays'], 'safe'],
[['appointment_date'], 'date','format' => 'd-M-yyyy H:m'],
and in web.php under component I have set
'formatter' => [
'defaultTimeZone' => 'UTC',
'timeZone' => 'Asia/Kolkata',
and in my view I am trying to format the date for display like this:
[
Yii::$app->formatter->asDatetime('appointment_date')
],
Now I am getting the error -
appointment_date' is not a valid date time value: DateTime::__construct(): Failed to parse time string (appointment_date) at position 0 (a): The timezone could not be found in the database
Array
(
[warning_count] => 1
[warnings] => Array
(
[6] => Double timezone specification
)
[error_count] => 3
[errors] => Array
(
[0] => The timezone could not be found in the database
[11] => Unexpected character
[12] => Double timezone specification
)
Whereas the date stored in the database is like : 2015-01-20 11:50:00
If I am not formatting the date and simply keeping the attribute in view as
appointment_date
then the date is shown as 2015-01-20 11:50:00
I want to show the date as 20-01-2015 11:50:00
If I am using the code like this:
[
'attribute'=>'appointment_date',
'format'=>['DateTime','php:d-m-Y H:i:s']
],
I am getting the date formatted correctly.
I want to know What I am doing wrong here in using
Yii::$app->formatter->asDatetime('appointment_date')
Thanks
I think it's just a small typo. You are passing in a string into the asDateTime
method where it needs the value
Yii::$app->formatter->asDatetime('appointment_date')
should be
Yii::$app->formatter->asDatetime($model->appointment_date)
Docs: http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html#asDatetime()-detail
OK it is as simple as that, I need to use
'appoinment_date:date'
or
'appointment_date:datetime'
and add the format in the component formatter
'formatter' => [
'defaultTimeZone' => 'UTC',
'timeZone' => 'Asia/Kolkata',
'dateFormat' => 'php:d-m-Y',
'datetimeFormat'=>'php:d-M-Y H:i:s'
and now it is working fine.
My DB type of date is date
so it is storing and giving response in "YYYY-DD-MM" formate.
I did this in view (index.php) without changing logic or DB Data.
initially it was
'date'
which I changed with this-
[
'attribute' => 'date',
'value' => function ($model, $key, $index, $widget) {
return date("d-m-Y", strtotime($model->date));
},
],
It is working fine for me,
Hope it will work for few more needy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With