What is Carbon in Laravel and How to use it?

Carbon is a PHP-based package that deals with date and time. It has simplified how to get dates and times with the desired format. The good thing is Laravel has included the Carbon package which means you don’t need to install it.

Using the carbon package you can do several tasks related to date and time. Below is the list that tells us what can be achieved by using the carbon package,

  • Set timezone in the application
  • Add days into the date
  • Get the difference between the two dates
  • Convert a date into the desired format

If you haven’t installed the Laravel framework you can follow the steps from this article.

Use Carbon in Laravel

Once the Laravel application is completely set up, you can use the Carbon class in it. Usually, we use the carbon class in the controller. Before using it you will need to import it through the namespace, so add below namespace in the controller where you want to use it.

use Carbon\Carbon;

Now you can use it in any method. Let’s start using it.

The carbon now() method returns the current date and time. Below is an example

$now = Carbon::now();
echo $now;
// Output: 2022-09-07 18:58:07

By default, the now() method takes timezone from PHP built-in method date_default_timezone_set(). It also accepts the timezone as an argument in case you want to change the timezone. See the below example

$now = Carbon::now('Europe/London');
echo $now;
// Output: 2022-09-07 20:00:21

You can also create an instance of carbon class that returns the same result as the now() method. It means carbon class instance and now() are equivalent.

$carbon = new Carbon();
echo $carbon;
// Output: 2022-09-07 19:15:07

Next, let’s use the today() method that returns the current day date.

$today = Carbon::today();
echo $today;
// Output: 2022-09-07 00:00:00