Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert timestamp to date in Laravel?

How can I return from the database all rows with a timestamp converted to a date (d-m-Y H:i), using the all() method?

It's not created_at or updated_at column, it's custom attribute, call it birthday if you wish.

like image 804
Jack Avatar asked Apr 17 '14 09:04

Jack


2 Answers

timestamp columns like created_at are being parsed first. the U is simply the timestamp format. you can return your own format. for other formats see date docs.

edit: as stated in my comment, getDateFormat() is for both ways (insert, selects). your best bet would be using format inside the model. example:

public function getMyBirthdayAttribute()
{
    return $this->my_birthday->format('d.m.Y');
}

use $model->my_birthday to call the attribute.

// controller
$posts = Post::all();

// within sometemplate.blade.php
@foreach($posts as $post)
    my formatted date: {{ $post->my_birthday }}
@endforeach
like image 180
Simon Wicki Avatar answered Sep 28 '22 11:09

Simon Wicki


The better way to manage dates with Laravel IMHO is to use the getDates accessor that is build into Laravel.

All you need to do is to set a method on your Model as such.

public function getDates()
{
    return [
        'my_birthday',
        'created_at',
        'updated_at',
    ];
}

This will return a Carbon object. Carbon is insanely awesome for manipulating dates.

It is what Laravel does by default to created_at and updated_at.

You can then do things like:

$my_birthday->diffForHumans()  // 2 Days ago
$my_birthday->format('d.m.Y')  // 20.02.1979

There are tons of helpers here for you. Check out the Carbon docs: https://github.com/briannesbitt/Carbon

Definitely worth learning. It might not be easy to understand for a beginner. However, I would advise you take a look and get your head around it. It will change your life - Dates can be a pain!

like image 41
T2theC Avatar answered Sep 28 '22 11:09

T2theC