将碳日期转换为 mysql 时间戳。

Converting a carbon date to mysql timestamp.

我在 mysql 数据库中有一个时间戳变量列。尝试将 carbon 时间戳转换为我可以在那里输入的内容,但是 Carbon::now() 只有 returns 一个 Carbon 对象,当我尝试使用 Carbon 对象的时间戳字符串时,它不会在 mysql。

public function store(CreateArticleRequest $request){
        $input = $request->all(); 
        var_dump($input); // JUST SO YOU CAN SEE
        $input['published_at'] = Carbon::now(); 
        var_dump($input); // JUST SO YOU CAN SEE
        Article::create($input);   
}

我的第一个 var dump 是这样的:

array (size=4)
  '_token' => string 'Wy67a4hWxrnfiGz61wmXfYCSjAdldv26wOJiLWNc' (length=40)
  'title' => string 'ASDFasdf' (length=8)
  'body' => string 'asdfasdf' (length=8)
  'published_at' => string '2015-08-26' (length=10)  

我的第二个 var dump 就是这样。

与 "published_at" 相关的 mysql 列是一个时间戳变量。我想如何将其从 Carbon Object 转换?

提前致谢。

问题出在您的日期字符串中,例如,您有这个:

public function setCrbDateAttribute($value)
{
     $this->attributes['crb_date'] = \Carbon\Carbon::createFromFormat('d-m-Y h:i', $value);
}

现在,如果有像 10-12-2014 这样的日期,则会出现此错误,因为缺少小时和分钟。因此,您确保日期包含所有参数,并确保日期字符串包含 - 作为分隔符而不是 /.

换句话说,在使用 Carbon 之前检查 $value 并确保您的日期字符串包含与您在该方法中使用的格式化字符串完全相同的格式。

这也发生在访问器方法中,所以在 Carbon::createFromFormat().

中使用它之前先检查日期值

如果您从用户输入中获取日期,然后在使用它之前使用日期或 date_format:format 规则验证日期,请在此处检查验证。

回答参考:

Laravel/Carbon Timestamp 0000-00-00 00:00:00 or Unexpected data found. Unexpected data found. Data missing

您还可以在模型上设置 Mutator。

public function setPublishedAt($value)
{
    $this->attributes['published_at'] = strtotime($value);
}

转换为时间戳

$model -> setPublishedAt('2015-08-26'); // 1440572400

或者您可以使用 strtotime

将日期转换为时间戳

strtotime — Parse about any English textual datetime description into a Unix timestamp

希望对您有所帮助。

简短的回答是 toDateTimeString() 是您要查找的内容:

$input['published_at'] = Carbon::now()->toDateTimeString();

有关更多选项,请参阅 http://carbon.nesbot.com/docs/,如果您只需要日期部分而不是时间,则包括 toDateString()

但更好的处理方法是让 Laravel 为您处理将日期值 to/from 转换为 Carbon 对象。参见 https://laravel.com/docs/5.4/eloquent-mutators#date-mutators