Hello i am usng laravel 4 for a app page, i love the carbon date functions but i have a problem with a date format. i have the date format something like:

dd/mm/yyyy

And i use :

\Carbon\Carbon::createFromTimeStamp(strtotime(Auth::user()->created_at))->diffForHumans() 

to show how old its something, but that works fine when the date format its

yyy-mm-dd

how can i only change one time the date format and not every time.

有帮助吗?

解决方案

You may try this:

$date = Auth::user()->created_at;
\Carbon\Carbon::createFromFormat('d/m/Y', $date)->diffForHumans();

Also you may try this (if you want to use createFromTimeStamp method):

$date = str_replace('/', '-', Auth::user()->created_at);
\Carbon\Carbon::createFromTimeStamp(strtotime($date))->diffForHumans();

其他提示

You can create an Accessor that will be used whenever you do echo $user->created_at:

public function getCreatedAtAttribute($attr)
{
    return Carbon::parse($attr)->diffForHumans();
}

More about Accessors: http://laravel.com/docs/eloquent#accessors-and-mutators

You can even put this in a BaseModel class and have all your Models extend the base class to automatically convert all created_at properties to your specified date format.

More easy global setup for date format in Laravel 4 : check this link

In fact, it's super easy to globally change date format using Carbon's lib. All you have to do is create a BaseModel.php file into Model Folder, then add methods for Created_At and Updated_at -> set attributes. Then, extend your model with this BaseModel and all dates are displaying with your own format.

I hope you'll enjoy this discover...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top