【问题标题】:Models column date format型号列日期格式
【发布时间】:2018-01-10 17:35:42
【问题描述】:

我修改了我的模型日期属性以计算生日,但现在当日期加载到我的表单中时(我使用表单集合)我得到它就像1979-07-17 00:00:00 正确的输出应该是1979-07-17

protected $dates = ['geburtstag'];

   public function age()
    {
        return $this->geburtstag->diffInYears(Carbon::now());
    }

我试图从模型中修改

protected $geburtstagFormat = 'Y-m-d';

但没有帮助。

在这种情况下我做错了什么

【问题讨论】:

    标签: date laravel-5 model format


    【解决方案1】:

    另一种方法 首先解析 $this->geburtstag->diffInYears(Carbon::now())

    $createdAt = Carbon::parse($this->geburtstag->diffInYears(Carbon::now()));
    

    然后就可以使用了

    $suborder['payment_date'] = $createdAt->format('M d Y');
    

    【讨论】:

      【解决方案2】:

      如果您不想存储出生时间,则应将数据库中的数据类型更改为date,而不是timestamp 或datetime。这将自动解决问题,因为当您在视图上调用属性时,这会准确提取它在数据库中的显示方式。否则,如果您想保持数据库不变,则必须在模型中定义一个 mutator,如下所示:

          public function getGeburstag($value){
              return Carbon::parse($value)->toDateString();
          }
      

      这会将geburtag 属性的原始值替换为其Y-m-d 格式的值。

      【讨论】:

      • 我将该字段设为日期,而建议的 mutator 在我的情况下不起作用
      【解决方案3】:

      你为什么不直接使用$model->geburtstag->format('Y-m-d')?

      您还可以在模型中创建一个mutaror,例如:

      public function getGeburstagDateAttribute($value) {
          return $this->geburtstag->format('Y-m-d');
      }
      

      并像这样使用它:

      $model->geburtstag_date // outputs geburtstag date in 'Y-m-d' format
      

      要在模型中设置日期格式,请在模型中使用protected $dateFormat = 'Y-m-d';。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        相关资源
        最近更新 更多