yii2:显示日期的格式

时间:2015-01-20 20:32:11

标签: php datetime yii2

我已在mysql db中将日期字段appointment_date配置为datetime字段。

在我的模型中,Appointment.php规则设置如下:

public function rules()
    {
        return [
            [['appointment_date','weekdays'], 'safe'],
            [['appointment_date'], 'date','format' => 'd-M-yyyy H:m'],

并在组件I下的web.php中设置了

'formatter' => [
        'defaultTimeZone' => 'UTC',
        'timeZone' => 'Asia/Kolkata',

在我看来,我正在尝试格式化显示日期,如下所示:

[
    Yii::$app->formatter->asDatetime('appointment_date')
 ],

现在我收到了错误 -

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
)

数据库中存储的日期如下:2015-01-20 11:50:00

如果我没有格式化日期并只是将属性保持在视图中 appointment_date然后日期显示为2015-01-20 11:50:00

我想将日期显示为20-01-2015 11:50:00

如果我使用的代码如下:

[
    'attribute'=>'appointment_date',
     'format'=>['DateTime','php:d-m-Y H:i:s']
            ],

我正确格式化日期。

我想知道我在使用

时做错了什么
Yii::$app->formatter->asDatetime('appointment_date')

由于

4 个答案:

答案 0 :(得分:7)

我认为这只是一个小错字。您将字符串传递到需要值

asDateTime方法中
Yii::$app->formatter->asDatetime('appointment_date')

应该是

Yii::$app->formatter->asDatetime($model->appointment_date)

文档:http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html#asDatetime()-detail

答案 1 :(得分:6)

好的就是这么简单,我需要使用

'appoinment_date:date'

'appointment_date:datetime'

并在组件格式化程序中添加格式

'formatter' => [
       'defaultTimeZone' => 'UTC',
       'timeZone' => 'Asia/Kolkata',
       'dateFormat' => 'php:d-m-Y',
       'datetimeFormat'=>'php:d-M-Y H:i:s'

现在工作正常。

答案 2 :(得分:0)

我的数据库日期类型为date,因此它会在" YYYY-DD-MM" 格式中存储和回复。
我在视图(index.php)中做了这个,没有改变逻辑或DB数据。

最初是

'date' 

我改变了这个 -

            [
                'attribute' => 'date',
                'value' => function ($model, $key, $index, $widget) { 
                    return date("d-m-Y", strtotime($model->date));
                },
            ],

对我来说这很好,
希望它能为更多有需要的人工作。

答案 3 :(得分:0)

将以下代码放在Project / config / web.php

的组件部分下
'formatter' => [
   'defaultTimeZone' => 'UTC',
   'timeZone' => 'Asia/Kolkata',
   'dateFormat' => 'php:d-m-Y',
   'datetimeFormat'=>'php:d-M-Y H:i:s'
   ]

如果您在网格中显示日期或日期时间,请添加此项 对于日期

'date_column_name:date'

日期时间

'datetime_column_name:datetime'

就是这样。它适用于您想要更改日期或日期时间格式的整个项目。