How to Manage Dates and Times in PHP Using Carbon
Time to read: 5 minutes
Date and time manipulation is one of a few frequently-experienced challenges of developing web apps in PHP. And one of it's most prevalent issues is identifying time disparities and making them readable, such as "one hour ago".
However, handling dates and times, and issues such as this, is greatly simplified by using Carbon; it's a library which reduces lengthy hours of coding and debugging to only a few lines of code. This is because Carbon, created by Brian Nesbit, extends PHP's own DateTime class and makes it much simpler to use.
If you've not heard of it before, it is self-described as:
A basic PHP API extension for DateTime
In this tutorial, you will learn Carbon's core features and capabilities, giving you the ability to far more easily manipulate date and time in PHP.
Prerequisites
To follow this tutorial you need the following components:
- PHP 8.3 or higher
- Composer installed globally
Installation
To install Carbon, first create a new project directory called carbon, change into the directory, and install the package, by executing the following commands:
Format dates using Carbon
With Carbon installed, in your editor or IDE, create a new PHP file, named index.php in the root of your project directory. Then, add the code below to index.php to include Composer's Autoloader file, vendor/autoload.php, and imported Carbon's core class.
Print dates
Now that Carbon's installed, let's start working through some examples, starting with the most essential: printing out some dates. To do that, we'll use carbon::today
to retrieve today's date via Carbon, which you can see in the example below.
Add that to index.php and then run it.
The output, which you can see an example of above, returns the current date, with the time being blank. However, if you update index.php to use carbon::now
instead, which you can see in the example below, you can retrieve the time along with the date.
After updating index.php and running it, you should see output similar to the example below, in your terminal.
In contrast to Carbon::now()
which returns the current date and time, and Carbon:today()
which only returns the current date, Carbon::yesterday()
and Carbon::tomorrow()
generate Carbon instances for yesterday and tomorrow, respectively, as in the examples below. today()
, yesterday()
, now
, and tomorrow()
are examples of common static instantiation helpers.
Create dates with precision
Carbon also allows us to generate dates and times based on a set of parameters. For example, to create a new Carbon
instance for a specific date use the Carbon::createFromDate()
method, passing in the year, month, day, and timezone, as in the following example.
You can also specify the time, by calling Carbon::create()
, passing in the year, month, day, timezone, hour, minute, and second, as in the following example
If any one or more of $year
, $month
, $day
, $hour
, $minute
, or $second
are set to null
their now()
equivalent values will be used. If $hour
is not null
, however, then the default values for $minute
and $second
will be 0
. If you pass in null
for any of those attributes, it will default to the current date and time.
Update index.php in your editor or IDE to match the code below and run it to see an example of all of these functions.
The create()
function in the first variable creates a Carbon
instance from date and time components; A timezone was supplied on the constructor to the second variable.
A Carbon object was constructed using date components with Carbon::createFromDate()
when initializing the third and fourth variables. Doing so generates a Carbon
instance based on just on a date.
It's worth pointing out that if no timezone is specified, your default timezone is used. However, if a timezone other than yours is specified, the timezone's actual time is supplied. The current time is set in the time section.
The final variable, initialized using Carbon::createFromTimestamp
, generates a date based on a timestamp.
Relative Modifiers
Another fantastic feature of Carbon is relative modifiers. These allow strings such as "next friday" or "a year ago" to be used when constructing Carbon
instances relative to the current date.
The following are examples of strings that are considered relative modifiers.
+
-
ago
first
next
last
this
today
tomorrow
Modify the date and time
When working with dates, you'll need to do more than just get the date and time. You'll frequently need to modify the date or time as well, such as adding a day or a week or subtracting a month.
A good example of needing this functionality is when building an affiliate program. In this scenario you'll want the affiliate cookie which the user receives to expire after a specified period of time, making the referral invalid.
Let's assume a cookie has a 90-day lifespan. With Carbon's add
and subtract
methods, we could compute that time quite trivially. The example below uses addDays()
to determine when the cookie expires.
It also uses some of the other add()
and sub()
methods which Carbon provides. If you're adding a single date, such as a day, you use addDay()
, but if you're adding several days, you use addDays()
. Using Carbon’s add and subtract methods can provide you with adjusted date and times.
Looking forward and back
Carbon also provides the next()
and previous()
functions which return the upcoming and previous occurrences of a particular weekday, which you can see an example of in the code below.
Format the date and time
Yet another fantastic option Carbon provides is the ability to format dates and times in whatever format that you desire. As Carbon is an expanded version of PHP's built-in date and time functions, Carbon can use PHP's built-in date formats via the format()
function. In addition, toXXXString()
methods are available to display dates and times with predefined formatting.
Other typical datetime formatting methods available to Carbon include the following.
Calculate relative time
The diffForHumans()
functions in Carbon also allow us to represent time in relative terms. Date/time discrepancies are frequently displayed in a so-called humanized format, such as in one year or three minutes ago.
Let's assume we're developing an extension for a blog CMS and we want to display the article's publish time in "hours ago" or the comments publish time in "hours ago".
First, the time and date the article was published, as well as other parameters, would be recorded in a database field. As a result, we extract the date from the database in the format Y-m-d H:i:s
and store it in a variable.
If the date in our database is August 4th, 2021, such as in the example below, you would use the carbonCreateFromFormat()
function to produce a Carbon date, and then use diffForHumans()
to find the difference.
If the date was saved as a timestamp, you can call Carbon::createFromTimestamp
.
Carbon also provides user translator services. So if your site makes use of a user's language preferences, call the language. If you have a user that speaks French, for example, all you have to do is call the function before the code, as seen below.
Output in this case would be, for example, 'il y a 2 mois'.
That's the essentials of managing dates and times in PHP using Carbon
In this tutorial, you learned how to install Carbon and its core functionality. However, Carbon has a great deal more functionality than has been covered in this tutorial. Check out their docs if you're keen to learn more about the available functionality.
Prosper Ugbovo is a webapp developer specializing in huge yet simple web apps. His writing strives to strike a balance between being instructive and meeting technological needs – but never at the price of being fun to read.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.