【问题标题】:Access to getDateFormat() from controller - Laravel从控制器访问 getDateFormat() - Laravel
【发布时间】:2016-10-01 11:28:33
【问题描述】:

是否可以从控制器或命令中访问 getDateFormat() 方法?

我可以像这样使用我的模型:

public function getCreatedAtAttribute($value)
    {
        $format = $this->getDateFormat();   
        return  Carbon::createFromFormat($format, $value, 'UTC')->setTimezone(\Helper::getTimezone());
    }

但是在我的控制器或命令中使用它时,例如$format = getDateFormat();,我收到以下错误:

local.ERROR: 异常 带有消息的“Symfony\Component\Debug\Exception\FatalErrorException” '调用未定义函数 App\Console\Commands\getDateFormat()'

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    当然不能——因为它是 Model 类的受保护方法。

    /**
     * Get the format for database stored dates.
     *
     * @return string
     */
    protected function getDateFormat()
    {
        return $this->dateFormat ?: $this->getConnection()->getQueryGrammar()->getDateFormat();
    }
    

    默认情况下它很简单

    /**
     * Get the format for database stored dates.
     *
     * @return string
     */
    public function getDateFormat()
    {
        return 'Y-m-d H:i:s';
    }
    

    Carbon 实例默认使用这种格式,因此如果您需要获取 Carbon 日期 - 只需使用 Carbon::parse($value) - 它肯定会识别这种格式。默认情况下,(string)Carbon::parse($value) 你会得到这种默认格式的日期:

    /**
     * Format to use for __toString method when type juggling occurs.
     *
     * @var string
     */
    protected static $toStringFormat = self::DEFAULT_TO_STRING_FORMAT;
    
    /**
     * Format the instance as a string using the set format
     *
     * @return string
     */
    public function __toString()
    {
        return $this->format(static::$toStringFormat);
    }
    

    还可以查看 Carbon 文档 - 有很多修饰符,例如 ->toDateString()->toDateTimeString()

    【讨论】:

      【解决方案2】:

      getDateFormat() 不是 php 中的本机函数,如果我记得它在 drupal 中的使用

      所以..

      如果在你的 $value 中有一个时间戳,你可以使用 getDate() 这将返回一个带有分钟 seconde 的数组 ...

      或者如果您的值不是时间戳,您可以使用 dateTime() 格式类似

      public function getCreatedAtAttribute($value)
          {
              $date = new DateTime($value);
              $date->format('Y-m-d H:i:s'); 
              return $date;
      
          }
      

      希望对你有帮助 美好的一天

      【讨论】:

      • GetDateFormat() 在 Laravel 中可用,就像我说的,我可以在我的模型中使用它,但不能在我的控制器中使用它。不知道为什么
      猜你喜欢
      • 2013-07-05
      • 2023-03-22
      • 2023-03-20
      • 2020-07-03
      • 2013-01-14
      • 2015-04-23
      • 2013-08-15
      • 2013-02-03
      • 2014-06-01
      相关资源
      最近更新 更多