Dealing with date and time in PHP can be frustrating, time consuming and complicated. Adding, subtracting dates, facing formatting issues, dealing with timezones, all can be a lot, especially if just you want a simple task with dates done. Here can help Carbon.
Carbon is a simple PHP package that extends the PHP DateTime class and supports all kind of operations with date and time. It makes dealing with date and time much easier and more semantic.
In this article, we will explore Carbon's core features and capabilities.
Table of Contents
Prerequisites
To follow this guide, you will need the following components:
- PHP 7.4 or higher
- Composer (installed globally)
Setting up the project
Before installing Carbon, first we need to create a new directory called carbon_tutorial, where we will install the Carbon package, and we will use as a working directory for this tutorial. We can do that by executing the following commands in a terminal:
mkdir carbon_tutorial
cd carbon_tutorial
composer require nesbot/carbon
In your editor or IDE, create a new PHP file, named index.php in the root of your directory carbon_tutorial. Next, we need to include the Composer's Autoloader file, vendor/autoload.php and import the Carbon's core class so we can use it:
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
Working with Carbon
Basic static functions
First, we will start with some basic functionality, retrieving the today's, tomorrow's and yesterday's dates. This can be achieved using the static helper functions, shown in the example below:
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
$today = Carbon::today();
$tomorrow = Carbon::tomorrow();
$yesterday = Carbon::yesterday();
echo "Today: $today \n";
echo "Tomorrow: $tomorrow \n";
echo "Yesterday: $yesterday \n";
If you execute the code above in your terminal, the output will display the today's, tomorrow's and yesterday's dates, with their time value set to 00:00:00:
Today: 2022-11-16 00:00:00
Tomorrow: 2022-11-17 00:00:00
Yesterday: 2022-11-15 00:00:00
There is also the static function now()
, that retrieves the time along with the date. In our index.php, append the following code snippet:
$now = Carbon::now();
echo "Now: $now \n";
The output produced from the code snippet above, should produce similar results as these:
Now: 2022-11-16 09:37:44
The static functions now()
, today()
, tomorrow()
and yesterday()
, can also accept a timezone parameter, which can help us retrieve a date in the particular timezone, except for the function now()
, which will return the current date and time in the particular timezone.
$now = Carbon::now('Pacific/Rarotonga');
$today = Carbon::today('Pacific/Rarotonga');
$tomorrow = Carbon::tomorrow('Pacific/Rarotonga');
$yesterday = Carbon::yesterday('Pacific/Rarotonga');
echo "Today: $today \n";
echo "Tomorrow: $tomorrow \n";
echo "Yesterday: $yesterday \n";
echo "Now: $now \n";
The code above, will retrieve the dates for today, tomorrow and yesterday for the timezone in the Cook Islands, Rarotonga, which has timezone UTC -10.
Today: 2022-11-15 00:00:00
Tomorrow: 2022-11-16 00:00:00
Yesterday: 2022-11-14 00:00:00
Now: 2022-11-15 23:49:20
Create specific dates
Beside the basic static functions, Carbon also supports another group of static helpers for creating date and time from a specific number of arguments. If omitted, Carbon provides default values for the current date, time and timezone. To demonstrate, we will define variables for a year, month, day, hour, minutes, seconds and timezone, and use them to create specific date in specific timezone.
$year = 2022;
$month = 5;
$day = 24;
$hour = 15;
$minutes = 25;
$seconds = 15;
$tz = 'Europe/Madrid';
echo Carbon::createFromDate($year, $month, $day, $tz);
echo Carbon::createFromTime($hour, $minutes, $seconds, $tz);
echo Carbon::createMidnightDate($year, $month, $day, $tz);
echo Carbon::create($year, $month, $day, $hour, $minutes, $seconds, $tz);
The function createFromDate()
will return a specific date in the specific timezone with a default time. On the other hand, createFromTime()
, will return a specific time in the specific timezone but with a default date. There is also the function createMidnightDate()
, that returns the supplied date in the timezone, but the time is set to midnight. And the last function create()
which accepts values for date, time and timezone to fully customize date and time. As for the output from executing the code, is displayed below.
2022-05-24 11:40:23
2022-11-23 15:25:15
2022-05-24 00:00:00
2022-05-24 15:25:15
Adding and Subtracting
Working with date and time, sometimes requires adding or subtracting a date, hour or even a month. Carbon has a lot of methods for adding or subtracting dates, months, centuries, years, quarters, weeks, hours, minutes, seconds, milliseconds, microseconds and even millennia.
For example, for adding a day you can use the function addDay()
, without passing any value. It also works if you pass a value, for example 5, to add 5 days. There is also a plural function addDays()
, that you can use to add more than one day. It comes done to a preference which one you use. In the add functions, you can also pass negative values, this is how the sub functions are implemented.
The API supports so many functions for addition and subtraction. Below are shown some of the functions that Carbon supports.
$datetime = Carbon::create(1918, 4, 5);
echo "Add a century: " . $datetime->addCentury() . " \n";
echo "Add 5 years: " . $datetime->addYears(5) . " \n";
echo "Subtract 7 quarters: " . $datetime->subQuarters(7) . " \n";
echo "Subtract 15 months: " . $datetime->subMonths(15) . "\n";
echo "Add 4 weekdays: " . $datetime->addWeekdays(4) . "\n";
echo "Subtract 55 weeks: " . $datetime->subWeeks(55) . "\n";
echo "Subtract one hour: " . $datetime->subHour() . "\n";
echo "Add 7 seconds: " . $datetime->addSeconds(7) . "\n";
echo "Add millenia: " . $datetime->addMillennia() . "\n";
Append the code above in the index.php and after executing it, you should get similar output as below:
Add a century: 2018-04-05 00:00:00
Add 5 years: 2023-04-05 00:00:00
Subtract 7 quarters: 2021-07-05 00:00:00
Subtract 15 months: 2020-04-05 00:00:00
Add 4 weekdays: 2020-04-09 00:00:00
Subtract 55 weeks: 2019-03-21 00:00:00
Subtract one hour: 2019-03-20 23:00:00
Add 7 seconds: 2019-03-20 23:00:07
Add millenia: 3019-03-20 23:00:07
There are much more methods that you can use, for more information you can read it here.
Comparison
Another very useful functionality is comparison of dates. Carbon supports different functions to achieve that. To show this, we will define two dates and then compare them and display whether they are equal, greater or less then. The functions return boolean, so for that purpose, we added a ternary operator to display the results.
$date1 = Carbon::create(2022, 10, 13, 15, 26, 14);
$date2 = Carbon::create(2022, 10, 15, 15, 26, 14);
echo "Is date1 equal to date2: " . ($date1->equalTo($date2) ? 'true' : 'false') . "\n";
echo "Is date1 not equal to date2: " . ($date1->notEqualTo($date2) ? 'true' : 'false') . "\n";
echo "Is date1 greater than date2: " . ($date1->greaterThan($date2) ? 'true' : 'false') . "\n";
echo "Is date1 greater than or equal to date2: " . ($date1->greaterThanOrEqualTo($date2) ? 'true' : 'false') . "\n";
echo "Is date1 less than date2: " . ($date1->lessThan($date2) ? 'true' : 'false') . "\n";
As with the other examples, append the code above to index.php and after executing the code in your terminal you should get the following output:
Is date1 equal to date2: false
Is date1 not equal to date2: true
Is date1 greater than date2: false
Is date1 greater than or equal to date2: false
Is date1 less than date2: true
Carbon also supports short hand aliases, that are shown in the table below with the PHP equivalent code.
$date1->equalTo($date2) |
$date1->eq($date2) |
$date1 == $date2 |
$date1->notEqualTo($date2) |
$date1->ne($date2) |
$date1 != $date2 |
$date1->greaterThan($date2) $date1->isAfter($date2) |
$date1->gt($date2) |
$date1 > $date2 |
$date1->greaterThanOrEqualTo($date2) |
$date1->gte($date2) |
$date1 >= $date2 |
$date1->lessThan($date2) $date1->isBefore($date2) |
$date1->lt($date2) |
$date1 < $date2 |
$date1->lessThanOrEqualTo($date2) |
$date1->lte($date2) |
$date1 <= $date2 |
Using Getters and Setters
With instantiating the Carbon class you can access the values as it was property with the help of getters. Also you can use setters to change the values.
First, we will try with the getter, to retrieve the values for the year, month, day, hour, minutes, seconds, day of the week, the day of the week in english and the month in english. Below are displayed the code that needs to be appended in index.php, and also is displayed the output that the should return.
$date = Carbon::now();
echo "Year: ". $date->year. "\n";
echo "Month: ". $date->month. "\n";
echo "Day: ". $date->day. "\n";
echo "Hour: ". $date->hour. "\n";
echo "Minutes: ". $date->minute. "\n";
echo "Seconds: ". $date->second. "\n";
echo "Day of the week: ". $date->dayOfWeek. "\n";
echo "English day of the week: ". $date->englishDayOfWeek. "\n";
echo "English month: ". $date->englishMonth. "\n";
Year: 2022
Month: 11
Day: 23
Hour: 15
Minutes: 44
Seconds: 37
Day of the week: 3
English day of the week: Wednesday
English month: November
Next, is trying to see how the setters work. We will change the values for year and month with accessing the properties.
$date->year = 1995;
$date->month = 5;
If now we execute the code with the getters, we can notice from the outputs that the values for the year and the month were changed:
Year: 1995
Month: 5
Day: 23
Hour: 15
Minutes: 54
Seconds: 38
Day of the week: 2
English day of the week: Tuesday
English month: May
You can also chain together the setters. Below is displayed the previous example using year()
and month()
$date->year(1995)->month(5);
Formatting Date and Time
Carbon supports methods that rely on the base class method DateTime::format()
. The methods toXXXString()
display dates and times with predefined formatting. You could also use the Carbon::format()
for custom formatting.
Append the following code in index.php and run it in your terminal to see the different types of string formatting that Carbon supports.
$date = Carbon::create(2022, 4, 12, 13, 45, 45);
echo $date->toDateString() . "\n";
echo $date->toFormattedDateString() . "\n";
echo $date->toTimeString() . "\n";
echo $date->toDateTimeString() . "\n";
echo $date->toDayDateTimeString() . "\n";
2022-04-12
Apr 12, 2022
13:45:45
2022-04-12 13:45:45
Tue, Apr 12, 2022 1:45 PM
Sometimes, the methods with the predefined formatting can't help us, so we need to use format()
for custom formatting of dates and time to fit our needs. For example, we want to produce the following output:
Thursday, 14th of October - 14:18:25 PM
We can solve this, with defining the values of the date and time and then custom formatting to achieve the output.
$date = Carbon::create(2021, 10, 14, 14, 18, 25);
echo $date->format('l, jS \of F - H:i:s A') . "\n";
In the table below, are described the format characters that were used.
Format character | Description |
---|---|
l |
Day of the month without leading zeros. English ordinal suffix for the day of the month, 2 characters |
jS |
A full textual representation of a month, such as January or March. |
Y |
A full numeric representation of a year, at least 4 digits, with - for years BCE. |
H:i:s |
24-hour format of an hour with leading zeros. Minutes with leading zeros. Seconds with leading zeros. |
A |
Uppercase Ante meridiem and Post meridiem. |
Calculating and Displaying the Relative Time
Carbon API also provides methods to display time relatively using the diff()
methods. These methods take a second date object as argument and returns a DateInterval instance. These methods always return the total difference expressed in the specified time requested. So, for example let's take two dates and retrieve the difference in days, weeks and hours between the dates. Also, we could use the diffForHumans()
method, that returns the difference between the dates in human readable format.
$date1 = Carbon::create(2022, 6, 24);
$date2 = Carbon::create(2022, 6, 7);
echo "Difference in days: " . $date1->diffInDays($date2) . "\n";
echo "Difference in weeks: " . $date1->diffInWeeks($date2) . "\n";
echo "Difference in hours: " . $date1->diffInHours($date2) . "\n";
echo "Difference in days (human format): " . $date1->diffForHumans($date2) . "\n";
Appending the code block in index.php and running the script in the terminal, should produce the following results. You could notice from the results, that the method diffForHumans()
returns a more human readable output indicating the period that passed between the dates.
Difference in days: 17
Difference in weeks: 2
Difference in hours: 408
Difference in days (human format): 2 weeks after
Conclusion
In this article, you got to explore the functionality and features of Carbon API. You got to manage date and time using Carbon.
If you'd like to dive deeper in Carbon, check out their documentation. Also the code of this tutorial is available on my Github.