2016-10-01 82 views
0

可以從控制器或命令訪問getDateFormat()方法嗎?從控制器訪問getDateFormat() - Laravel

我可以用它在我的模型是這樣的:在我的控制器或命令使用它的時候,像這樣$format = getDateFormat();

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

但是,我得到以下錯誤:

local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined function App\Console\Commands\getDateFormat()'

回答

0

當然,你不能 - 因爲它是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::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); 
} 

還要檢查碳文檔 - 有很多像->toDateString()改性劑,->toDateTimeString()

+0

超級,謝謝@Silwerclaw – user3489502

0

getDateFormat()不在php中的本地函數,如果我記住它在drupal中的使用

so ..

如果在$值你有一個戳,你可以使用這個getDate()將返回微小的Seconde系列陣列...

,或者如果你的價值是不是時間戳您可以使用dateTime()與格式,與

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

    } 

我希望這可以幫助你 美好的一天

+0

GetDateFormat()可爲Laravel,像我說,我可以使用它我的模型,但不是在我的控制器。不知道爲什麼 – user3489502