user11124425
user11124425

Reputation: 971

the format time on laravel

I would like to know how to recuperate the format time on my form please? For example start_time => 20:00 and end_time 22:00.

In my table course I have this

public function up()
    {
        Schema::create('course', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date_seance');
            $table->time('start_time');
            $table->time('end_time');
            $table->timestamps();
        });
    }

Then, on my model course I have this

class Course extends Model
{
    //
    protected $dates = ['date_seance', 'start_time', 'end_time'];
}

In my view index.blade

@foreach($course as $item)
<tr>
   <td> {{$item->date_seance->format('d/m/Y') }}</td>
   <td> {{$item->start_time}}</td>
   <td> {{$item->end_time}}</td>

Thank you for your help.

Upvotes: 2

Views: 3344

Answers (6)

carlitoxenlaweb
carlitoxenlaweb

Reputation: 31

I know it's old but why not try a simple cast on model? Something like:

class Course extends Model
{
    protected $casts = [
        'date_seance' => 'datetime:d/m/Y',
        'start_time'  => 'datetime:H:i',
        'toend_time' => 'datetime:H:i',
    ];
}

Check the docs here if you need more cast's types: https://laravel.com/docs/10.x/eloquent-mutators#attribute-casting

Upvotes: 0

Afraz Ahmad
Afraz Ahmad

Reputation: 5386

Use Mutators and Accessors.

  1. A Mutator setStartTimeAttribute to save time in database
  2. An Accessor getStartTimeAttribute to show it with required format i.e. h:i or H:i

    public function setStartDateAttribute($value)
    {
        $this->attributes['start_time'] = Carbon::parse($value)->format('H:i');
    }
    public function getStartDateAttribute()
    {
         return Carbon::parse($this->attributes['start_time'])->format('H:i');
    }
    

Now you can access formatted time as $object->start_time i.e. 20:00

Upvotes: 2

Cl&#233;ment Baconnier
Cl&#233;ment Baconnier

Reputation: 6058

I don't think you can use 'start_time' and 'end_time' in date since they are not.

class Course extends Model
{
    protected $dates = ['date_seance'];
}

Then use

<td> {{$item->date_seance->format('d/m/Y') }}</td>
<td> {{date('H:i', strtotime($item->start_time)) }}</td>
<td> {{date('H:i', strtotime($item->end_time)) }}</td>

Upvotes: 0

Prince Kumar Dwivedi
Prince Kumar Dwivedi

Reputation: 257

try below format you already stored in time so no need to convert in strtotime

<td> {{date('H:i', $item->start_time) }}</td>

Upvotes: 0

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should try this:

<td> {{date('d/m/Y H:i', strtotime($item->date_seance)) }}</td>

Upvotes: -1

Ahmed Atoui
Ahmed Atoui

Reputation: 1556

the type of column is instance of Carbon class what about trying this :

 <td> {{$item->date_seance->toDateString() }}</td>

Upvotes: 0

Related Questions