php - How can I change a column time attribute to AM and PM for the blade view?

I have a table namedtime_entries
and the column name istime_start
.
I'm insertingCarbon::now();
on it. The data stored in the column is2021-08-26 09:51:37
andblade.php
shows same result.
ModelTimeEntry
:
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TimeEntry extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function getTimeStartAttribute($value)
{
return Carbon::createFromFormat('H:i:s', $value)->TimeString();
}
}
Controller:
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\TimeEntry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AttendanceController extends Controller
{
public function index()
{
$data = TimeEntry::where('user_id', Auth::user()->id)->paginate(2);
return view('Admin.Attendance-History-page', compact('data'));
}
}
Blade view:
<tbody id="table_data">
@foreach ($data as $punch)
<tr>
<td>{{ $punch->user->name }}</td>
<td>{{ $punch->user->employee_id }}</td>
<td>19 Feb 2019</td>
<td>{{ $punch->time_start }} </td>
<td>{{ $punch->time_end }}</td>
<td>9 hrs</td>
<td>
<span class="badge bg-inverse-success">Perfect</span>
</td>
<td>0</td>
</tr>
@endforeach
</tbody>
I want to know how can I format the output from2021-08-26 09:51:37
to something like09:51:AM
in Blade?
Thank you for your help.
Answer
Solution:
There is a straight forward solution for this using the PHPdate()
method.
{{ date('h:m A', strtotime($punch->time_start)) }}
This will output09:51 AM
If you want to output09:51:AM
then just add:
after them
and remove the space, like so:
{{ date('h:m:A', strtotime($punch->time_start)) }}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object of class stdclass could not be converted to string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.