Are you curious to know what uses the Carbon package is in Laravel? Working with dates and times in PHP may not be easy because the issue of date and time has its problems for PHP developers. Working with PHP functions such as start time, date and time formatting problems, multiple computations, and… Examples of challenges are encountered when working with date and time in PHP.
The Carbon package is designed to work with data and time in PHP and is installed with Laravel by default. Brian Nesbit developed this package, and its various methods make working with date and time in PHP language and Laravel framework much easier. Also, using the carbon package, date and time codes are much more semantically or semantically readable; As a result, the code will be better maintained and developed.
In the rest of this article, we will teach you how to install the Carbon package in Laravel. Then we will examine the methods of this package in practice. Stay with us.
What are the uses of the Carbon package in Laravel?
The Laravel Carbon package inherits from its DateTime PHP class. The carbon package provides great features for working with date and time in PHP and Laravel, including:
- Specify a Timezone
- Access the current time
- Convert Datetime for more readability
- Convert an English phrase to Datetime
- Decrease and add date and time
- Date and time comparison
- More code readability semantically
The above forces PHP and Laravel developers to use this application package to work with date and time in PHP. In the following, we will explain how to install the Carbon package.
How to install Carbon package in Laravel
To use the Carbon package, you only need to use its Namespace. Fortunately, this package is installed by default with Laravel, and we do not need to add it with Composer:
<? php
use Carbon \ Carbon ;
Now that we’ve added Namespace let’s take a look at the various features of this package.
Getting started with the Carbon package in Laravel
To get started with the Carbon package, we can create a new instance of this class and then call different methods on it:
$ carbon = new Carbon;
The created object has a public property called date. The value is a string containing the date and time. Here we have another public property called timezone_type, whose value is an integer, and a public property called timezone, in which the time range value is set as a string.
Another way to use Carbon methods is to call static methods directly from the Carbon class without having to create a new instance. In the rest of this article, we will use this method.
Get a specific time and date in Laravel with a carbon package
To capture a Carbon object related to a time and date, such as now, yesterday, and the like, you can use the following methods:
// get the current time - 2021-01-14 10:10:54
$ current = Carbon :: now ();
// get today - 2021-01-14 00:00:00
$ today = Carbon :: today ();
// get yesterday - 2021-01-13 00:00:00
$ yesterday = Carbon :: yesterday ();
// get tomorrow - 2021-01-15 00:00:00
$ tomorrow = Carbon :: tomorrow ();
You can also convert a Carbon object to a Carbon object by passing a string when creating an instance:
// parse a specific string - 2021-01-01 00:00:00
$ newYear = new Carbon ( 'first day of January 2021' );
// set a specific timezone - 2021-01-01 00:00:00
$ newYearPST = new Carbon ( 'first day of January 2021' , 'America \ Pacific' );
You can pass this string in various forms; for example:
$ carbon = new Carbon ( 'November 5th 2021' );
$ carbon = new Carbon ( '5th November 2021' );
$ carbon = new Carbon ( '20211105' );
$ carbon = new Carbon ( '2021/11/5' );
$ carbon = new Carbon ( '21 -11-05 ' );
$ carbon = new Carbon ( '2021-11-05' );
You can pass this string temporarily or later than the current time when creating a sample of the Carbon class:
$ carbon = new Carbon ( '-3 days' );
$ carbon = new Carbon ( '-4 weeks' );
$ carbon = new Carbon ( '-5 years' );
$ carbon = new Carbon ( '+2 days 9 hours' );
$ carbon = new Carbon ( '+3 weeks 4 days' );
$ carbon = new Carbon ( '+3 years 1 months 1 day 5 hours 33 minutes 25 seconds' );
We can create a Carbon object with a certain number of input parameters using the following methods:
Carbon :: createFromDate ( $ year , $ month , $ day , $ tz );
Carbon :: createFromTime ( $ hour , $ minute , $ second , $ tz );
Carbon :: create ( $ year , $ month , $ day , $ hour , $ minute , $ second , $ tz );
If you set any of the above parameters to null, default, the current value will be considered.
You can also use the createFromFormat method to create your format for creating a Carbon object. For example:
$ newDateTime = Carbon :: createFromFormat ( 'Ymd H: i: su' , '2021-02-01 03:45: 27.612584' );
To view different date and time formats in PHP, visit the DateTime Formats page on the official PHP website.
Formatting Date and Time in PHP
You can use the various methods provided by this package to convert a created Carbon object to a string of a specific format. for example:
$ newDateTime = Carbon :: create ( 2021 , 11 , 05 , 11 , 45 , 21 , 'UTC' );
$ newDateTime -> toDateTimeString ()
// output: '2021-11-05 11:45:21'
$ newDateTime -> toAtomString ()
// output: '2021-11-05T11: 45: 21 + 00: 00'
$ newDateTime -> toCookieString ()
// output: 'Friday, 05-Nov-2021 11:45:21 UTC'
$ newDateTime -> toDayDateTimeString ()
// output: 'Fri, Nov 5, 2021 11:45 AM'
$ newDateTime -> toFormattedDateString ()
// output: 'Nov 5, 2021'
$ newDateTime-> toTimeString ()
// output: '11: 45: 21 '
$ newDateTime -> toDateString ()
// output:' 2021-11-05 '
You can use the format method to convert to your favorite format:
$ newDateTime -> format ( 'l jS \\ of FY h: i: s A' )
// output: 'Friday 5th of November 2021 11:45:21 AM'
Decrease and increase date and time in PHP
When it comes to date and time, capturing and formatting date and time are not the only things we need. In most cases, a series of simple calculations seems necessary.
For example, when you want to give a user a limited trial or subscription, you need the user subscription to expire after a limited time. We can do this easily and use the increase and decrease methods in the Carbon package.
// get the current time
$ current = Carbon :: now ();
// add 30 days to the current time
$ trialExpires = $ current -> addDays ( 30 );
Here are a series of increase and decrease methods that vary from seconds to years, based on the Carbon package documentation:
$ dt = Carbon :: create ( 2021 , 1 , 31 , 0 );
echo $ dt -> toDateTimeString (); // 2021-01-31 00:00:00
echo $ dt -> addYears ( 5 ); // 2026-01-31 00:00:00
echo $ dt -> addYear (); // 2027-01-31 00:00:00
echo $ dt -> subYear (); // 2026-01-31 00:00:00
echo $ dt -> subYears ( 5 ); // 2021-01-31 00:00:00
echo $ dt -> addMonths (60 ); // 2026-01-31 00:00:00
echo $ dt -> addMonth (); // 2026-03-03 00:00:00 equivalent of $ dt-> month ($ dt-> month + 1); so it wraps
echo $ dt -> subMonth (); // 2026-02-03 00:00:00
echo $ dt -> subMonths ( 60 ); // 2021-02-03 00:00:00
echo $ dt -> addDays ( 29 ); // 2021-03-03 00:00:00
echo $ dt -> addDay (); // 2021-03-04 00:00:00
echo $ dt -> subDay (); // 2021-03-03 00:00:00
echo $ dt -> subDays ( 29 ); // 2021-02-03 00:00:00
echo $ dt -> addWeekdays ( 4 ); // 2021-02-09 00:00:00
echo $ dt -> addWeekday (); // 2021-02-10 00:00:00
echo $ dt -> subWeekday (); // 2021-02-09 00:00:00
echo $ dt -> subWeekdays ( 4 ); // 2021-02-03 00:00:00
echo $ dt -> addWeeks ( 3 ); // 2021-02-24 00:00:00
echo $ dt-> addWeek (); // 2021-03-02 00:00:00
echo $ dt -> subWeek (); // 2021-02-24 00:00:00
echo $ dt -> subWeeks ( 3 ); // 2021-02-03 00:00:00
echo $ dt -> addHours ( 24 ); // 2021-02-04 00:00:00
echo $ dt -> addHour (); // 2021-02-04 01:00:00
echo $ dt -> subHour (); // 2021-02-04 00:00:00
echo $ dt -> subHours ( 24 ); // 2021-02-03 00:00:00
echo $ dt -> addMinutes ( 61 ); // 2021-02-03 01:01:00
echo $ dt -> addMinute (); // 2021-02-03 01:02:00
echo $ dt -> subMinute (); // 2021-02-03 01:01:00
echo $ dt -> subMinutes ( 61 ); // 2021-02-03 00:00:00
echo $ dt -> addSeconds ( 61 ); // 2021-02-03 00:01:01
echo $ dt -> addSecond (); // 2021-02-03 00:01:02
echo $ dt -> subSecond (); // 2021-02-03 00:01:01
echo $ dt -> subSeconds ( 61 ); // 2021-02-03 00:00:00
Compare Date and Time in PHP
Using the Carbon package in Laravel, we can compare different times. Here are some examples from the Carbon package documentation:
$ first = Carbon :: create ( 2021 , 9 , 5 , 23 , 26 , 11 );
$ second = Carbon :: create ( 2021 , 9 , 5 , 20 , 26 , 11 , 'America / Vancouver' );
var_dump ( $ first -> equalTo ( $ second )); // bool (false)
var_dump ( $ first -> notEqualTo ( $ second )); // bool (true)
var_dump ( $ first -> greaterThan ( $ second )); // bool (false)
var_dump ( $ first -> greaterThanOrEqualTo ( $ second )); // bool (false)
var_dump ( $ first -> lessThan ( $ second )); // bool (true)
var_dump ( $ first -> lessThanOrEqualTo ( $ second )); // bool (true)
The abbreviated form of these methods can also be used as follows:
var_dump ( $ first -> eq ( $ second )); // bool (false)
var_dump ( $ first == $ second ); // bool (false)
var_dump ( $ first -> ne ( $ second )); // bool (true)
var_dump ( $ first ! = $ second ); // bool (true)
var_dump ( $ first -> gt ( $ second )); // bool (false)
var_dump ( $ first -> isAfter ( $ second )); // bool (false)
var_dump ( $ first > $ second ); // bool (false)
var_dump ( $ first -> gte ( $ second )); // bool (false)
var_dump ( $ first > = $ second ); // bool (false)
var_dump ( $ first -> lt ( $ second )); // bool (true)
var_dump ( $ first -> isBefore ( $ second )); // bool (true)
var_dump ( $ first < $ second); // bool (true)
var_dump ( $ first -> lte ( $ second )); // bool (true)
var_dump ( $ first <= $ second ); // bool (true)
Getters and Setters in Carbon Package
To change the date and time or get it, you can use Getters and Setters as follows:
$ dt = Carbon :: now ();
// set some things
$ dt -> year = 2015 ;
$ dt -> month = 04 ;
$ dt -> day = 21 ;
$ dt -> hour = 22 ;
$ dt -> minute = 32 ;
$ dt -> second = 5 ;
// get some things
var_dump ( $ dt -> year);
var_dump ( $ dt -> month);
var_dump ( $ dt -> day);
var_dump ( $ dt -> hour);
var_dump ( $ dt -> second);
var_dump ( $ dt -> dayOfWeek);
var_dump ( $ dt -> dayOfYear);
var_dump ( $ dt -> weekOfMonth);
var_dump ( $ dt -> daysInMonth);
We can call Setter methods in chains:
$ dt = Carbon :: now ();
$ dt -> year ( 1975 ) -> month ( 5 ) -> day ( 21 ) -> hour ( 22 ) -> minute ( 32 ) -> second ( 5 ) -> toDateTimeString ();
$ dt -> setDate ( 1975 , 5 , 21 ) -> setTime ( 22 , 32 , 5 ) -> toDateTimeString ();
$ dt -> setDateTime ( 1975 , 5 , 21 , 22 , 32 , 5 ) -> toDateTimeString ();
Get relative time in PHP
The carbon package allows us to display time in relative terms using diff methods. For example, suppose we have a blog, and we want to display the time of publication, for example, 3 hours ago. To do this, we can easily use diff methods.
Find the time difference in PHP.
The following methods are used to find the difference number:
$ current = Carbon :: now ();
$ dt = Carbon :: now ();
$ dt = $ dt -> subHours ( 6 );
echo $ dt -> diffInHours ( $ current ); // -6
echo $ current -> diffInHours ( $ dt ); // 6
$ future = $ current -> addMonth ();
$ past = $ current -> subMonths ( 2 );
echo $ current -> diffInDays ( $ future ); // 31
echo $ current -> diffInDays ( $ past); // -62
The display time difference for the user
Sometimes we need to show the time difference to the user in a readable way. Using the diffForHumans method, we can find the difference and display it legibly to the user. for example:
$ dt = Carbon :: now ();
$ past = $ dt -> subMonth ();
$ future = $ dt -> addMonth ();
echo $ dt -> subDays ( 10 ) -> diffForHumans (); // 10 days ago
echo $ dt -> diffForHumans ( $ past ); // 1 month ago
echo $ dt -> diffForHumans ( $ future ); // 1 month before
Solar Date in PHP
As you know, the Carbon package works by AD. You can use the morilog / Jalali package to work with the solar date, which we introduced in the best Laravel packages article. Using the morilog / Jalali package is very similar to the Carbon package.
Additional resources
To see all the methods in the Carbon package, which are very numerous and varied, you can refer to the official documentation of the Carbon package.
Conclusion
In this article from the Laravel training series, we got acquainted with the extraordinary features of the Carbon package for working with date and time in Laravel, and we learned the most practical methods. You can use this package and its methods in the same way in your PHP projects; You just have to install it with Composer first. We hope you find the content in this article useful and informative. We are happy to share your comments, experiences, and questions with other SunLearn users.