Last updated on December 29, 2022
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,
If you haven’t installed the Laravel framework you can follow the steps from this article.
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
In above we have learned about carbon’s now() and today() function. The difference is today() function returns only the date whereas the now() function returns the current date and time.
Carbon is a package that provides functions to deal with date and time in PHP in an easy way. It has some nice functions that usage is very easy. For example, if you want to get today’s date then the today() function helps you to get it. Similarly to get yesterday’s date, you can use the yesterday() function.