laravel迁移的时间格式?

时间:2018-04-19 16:17:09

标签: php laravel time

我希望有一个输入,您可以在欧洲格式中输入时间,如12:00或21:34。 (HH:MM) 我该怎么做?

private val lifecycleListener: SampleLifecycleListener by lazy {
    SampleLifecycleListener()
}

这就是我所拥有的,但它显然是错误的。

5 个答案:

答案 0 :(得分:1)

您可以使用Carbon执行此操作,默认情况下包含在Laravel中:

  1. 使用当前时间$date = Carbon::now()
  2. 设置变量
  3. 设置小时,例如22 $date->hour = 22
  4. 设置分钟,例如54 $date->minutes = 54
  5. 最后,设置$table->date($date)

答案 1 :(得分:1)

在laravel 5.6中,您有这个新功能,您可以投射时间戳,以便您的迁移应该像这样

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('arena');
    $table->timestamp("begin");
    $table->timestamps();
});

在您的Post模型中,您只需执行此操作:

protected $casts = [
    'begin' => 'date:hh:mm'
];

修改
如果你没有使用laravel 5.6,你可以使用Accessors & Mutators轻松操作数据库设置数据或从数据库获取数据,这样你就可以做到这样的事情

public function getBeginAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('hh:mm');
}

每当您在刀片中或在此{{ $post->begin }}的任何地方回显它时,它会自动更改您的格式。

希望有所帮助。

答案 2 :(得分:0)

由于laravel迁移基于传统的SQL约定,因此无法使用迁移更改格式。这是因为SQL datetime本身的格式为YYYY-MM-DD HH:MM:SS。但您可以使用碳日期时间格式根据您的意愿显示存储的日期,时间或两者。 有关Carbon的更多信息,请参阅此linkOfficial Link Here

答案 3 :(得分:0)

“Class'App \ Carbon \ Carbon'未找到”

这是我的帖子控制器

<?php
use Carbon\Carbon;
namespace App;

use Illuminate\Database\Eloquent\Model;


class Post extends Model
{

    protected $fillable=['post','user_id'];

    public function user(){
        return $this->belongsTo(User::class);
    }


    public function comments(){
        return $this->morphMany(Comment::class, 'commentable');
    }

    public function getCreatedAtAttribute($date)
    {
        return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
    }

    public function getUpdatedAtAttribute($date)
    {
        return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
    }
}

答案 4 :(得分:0)

您可以使用$table->times('field_name');

Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('arena');
$table->times("begin");
$table->timestamps();

});