Time format in laravel migration?

2020-07-18 09:28发布

I want to have an input, where you put a time in EU format like 12:00 or 21:34. (hh:mm) How do I do that?

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

This is what I have, but it's obviously wrong.

标签: php laravel time
4条回答
Root(大扎)
2楼-- · 2020-07-18 10:02

You can use $table->time('field_name');

Schema::create('posts', function (Blueprint $table) {
   $table->increments('id');
   $table->string('title');
   $table->string('arena');
   $table->time("begin");
   $table->timestamps();
});
查看更多
疯言疯语
3楼-- · 2020-07-18 10:13

Since laravel migration is based on traditional SQL convention, you cannot change the format using migration. This is because SQL datetime itself is formatted as YYYY-MM-DD HH:MM:SS. But you can use Carbon date time format to show the stored date, time or both as per you wish. Refer to this link for more on Carbon. Official Link Here

查看更多
贼婆χ
4楼-- · 2020-07-18 10:25

In laravel 5.6 you have this new feature that you can cast your timestamp so your migration should be like this

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

And in your Post model you can simply do this:

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

Edit
If you are NOT using laravel 5.6 you can use Accessors & Mutators to easily manipulate data on setting on database or getting it from database so you can do something like this

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

And every time that you echoing it out in your blade or wherever like this {{ $post->begin }} it automatically changes the format for you.

Hope that helps.

查看更多
等我变得足够好
5楼-- · 2020-07-18 10:26

You could do this with Carbon, which is included in Laravel by default:

  1. Set a variable with the current time $date = Carbon::now()
  2. Set hour, for example 22 $date->hour = 22
  3. Set minutes, for example 54 $date->minutes = 54
  4. Finally, set $table->date($date)
查看更多
登录 后发表回答