How to set date time using Carbon in Laravel

The Carbon PHP API helps deals many complex situations when working with dates, times and time zones in a Laravel application. To manipulate data form a Date function, you need to format and parse it in different forms. Lets go through how we can set date time in different formats using the Carbon API in Laravel.

Format date using Carbon in Laravel Blade File

Many times during application development, we need the date variable to show up in different formats in a view file. The code below shows how using the Carbon API, we can pass any format and make the date appear accordingly.

It parses the date from $user->from_date variable and formats in the form ‘d/m/Y’. You can enter any other format type, the Carbon API will preview date in the entered format and show up in the blade file.

{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}

Create date in a format using Carbon

You can also create a new date and pass it to a variable of a specific format using Carbon, as shown below.

Carbon::createFromFormat('Y-m-d H:i:s', $request->date)->format('d-m-Y')

Set date time to human readable form

The versatile library also has functions that auto format a created date to human readable forms. The syntax for this helper function is as shown below.

$comment->created_at->diffForHumans();