How to use Carbon PHP API in Laravel?

Carbon is a useful PHP API inherited from the PHP DateTime class. It deals with times, time zones and many other date and time related functions.

The package helps makes working with date and time in PHP easier and more semantic making the code simpler, more readable and maintainable. Some of the important use cases of the Carbon PHP API are as shown below.

Use Carbon in Laravel

To install an API or package, you need to pass the installation command in the Laravel directory. However, for Carbon, it is added in the Laravel package by default. So whenever you want to use the API, just add an import for it, as shown below.

<?php
use Carbon\Carbon;

Or add it with the Illuminate\Support\Carbon Class as follows.

<?php
 
// namespace App\....
 
use Illuminate\Support\Carbon;

Now, you can use Carbon with various helper methods, to get relevant information. For example as shown below.

$now = Carbon::now();
$today = Carbon::today();
$tomorrow = Carbon::tomorrow('Europe/London');
$yesterday = Carbon::yesterday();

Examples of Carbon use cases in Laravel

Format date in Laravel using Carbon

$formateddate = Carbon::parse($date)->format('M d Y');

Create a date and time

$dt = Carbon::create(2012, 1, 31, 0);

echo $dt->toDateTimeString();

// outputs
// 2012-01-31 00:00:00