Convert timestamp to date in Laravel?

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

This is not a column created_ator updated_at, it is a custom attribute, name it birthdayif you want.

+5
source share
4 answers

In this case, you need to convert the date to query, if mysqlused as your database, then you can use a raw query, for example:

// Assumed my_birthday is like 1255033470
$raw = DB::raw("date_format(from_unixtime(my_birthday),'%b %d, %Y %l:%i %p') as dob");
$result = Model::get(array('id', 'username', $raw));

You can write it in one line:

$result = Model::get(array('id', 'username', DB::raw("...")));
+2
source
Columns

timestamp, created_at, . U - . . . date docs.

edit: , getDateFormat() (, ). . :

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

$model->my_birthday .

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

// within sometemplate.blade.php
@foreach($posts as $post)
    my formatted date: {{ $post->my_birthday }}
@endforeach
+8

Laravel IMHO - getDates, Laravel.

, , .

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

Carbon. .

, Laravel created_at updated_at.

, :

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

. Carbon: https://github.com/briannesbitt/Carbon

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

+7
source

Just put this in your $ post code, it depends on what you create

$post ->created_at->format('d.m.Y')
0
source

Source: https://habr.com/ru/post/1536918/


All Articles