Working with date and time in PHP can be complicated. You often have to juggle strtotime, formatting issues, manual calculations, and time zones.
The Carbon package helps make dealing with date and time in PHP and Laravel much easier and more semantic so that your code is more readable and maintainable.
Carbon is a package by Brian Nesbitt that extends PHP’s own DateTime class. Laravel uses Carbon under the hood for Eloquent timestamps and date casting, so learning it will make working with any created_at or updated_at field feel natural.
Carbon provides functionality such as:
Dealing with time zones.
Getting the current time easily.
Converting a datetime into something readable.
Parsing an English phrase into datetime (
"first day of January 2016").Adding and subtracting dates (
"+ 2 weeks","-6 months").A semantic and chainable way of dealing with dates.
In this article, you will install Carbon where needed and explore the features and functionality that it provides in both raw PHP and Laravel applications.
Carbon builds on PHP DateTime: Carbon extends the built in
DateTimeclass with a fluent, chainable API, so anything you can do withDateTimecan be done through Carbon with clearer code.Laravel integrates Carbon automatically: Eloquent model date attributes are returned as Carbon instances when you use
$castsor$dates, which means you can call Carbon methods directly on fields likecreated_at.Mutability and CarbonImmutable matter: The default
Carbonclass is mutable, so methods likeaddDaysmodify the instance in place, whileCarbonImmutablealways returns a new instance and keeps the original unchanged.Time zone handling is first class: Carbon makes it straightforward to store datetimes in UTC, convert them to a user’s time zone when needed, and avoid common offset mistakes.
Relative and formatted output is simple: Helpers such as
diffForHumans()andtoDateTimeString()cover common user facing formats without custom parsing logic.
This tutorial was verified with PHP v8.0.5, Composer v2.0.13, MySQL 8.0.24, Laravel v8.40.0, and Carbon v2.31. The core Carbon concepts apply to more recent Laravel and PHP versions as well, including Laravel 10 and 11.
In order to use Carbon, you’ll need to import Carbon from the Carbon namespace. In standalone PHP projects you can install it via Composer:
composer require nesbot/carbonIn Laravel applications, Carbon is already included and wired into Eloquent’s date handling.
Whenever you need to use Carbon directly, you can import it like so:
<?php
use Carbon\Carbon;After importing, let’s explore what Carbon provides and how Laravel returns Carbon instances for model attributes out of the box.
Get the current time:
$current = Carbon::now();Current time can also be retrieved with this instantiation:
$current2 = new Carbon();Get today’s date:
$today = Carbon::today();Get yesterday’s date:
$yesterday = Carbon::yesterday();Get tomorrow’s date:
$tomorrow = Carbon::tomorrow();Parse a specific string:
$newYear = new Carbon('first day of January 2016');This returns:
Output2016-01-01 00:00:00These helpers provide human-readable requests for frequent date and time needs like today(), yesterday(), and tomorrow().
In addition to the quick ways to define date and times, Carbon also let’s us create date and times from a specific number of arguments.
createFromDate() accepts $year, $month, $day, $tz (time zone):
Carbon::createFromDate($year, $month, $day, $tz);createFromTime() accepts $hour, $minute, $second, and $tz (time zone):
Carbon::createFromTime($hour, $minute, $second, $tz);create() accepts $year, $month, $day, $hour, $minute, $second, $tz (time zone):
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);These are very helpful when you get some sort of date or time in a format that isn’t normally recognized by Carbon. If you pass in null for any of those attributes, it will default to current.
Grabbing the date and time isn’t the only thing you’ll need to do when working with dates. You’ll often need to manipulate the date or time.
For instance, when creating a trial period for a user, you will want the trial period to expire after a certain amount of time. So let’s say we have a 30-day trial period. We could calculate that time with Carbon’s add and subtract.
For this example, we can use addDays() to determine when the trial expires:
// get the current time
$current = Carbon::now();
// add 30 days to the current time
$trialExpires = $current->addDays(30);From the Carbon documentation here are some of the other add() and sub() methods available to us.
Consider a date set to January 31, 2012:
$dt = Carbon::create(2012, 1, 31, 0);
echo $dt->toDateTimeString();This will return:
Output2012-01-31 00:00:00Modifying the date with addYears() and subYears() will result in the following:
Command | Output |
|---|---|
| 2012-01-31 00:00:00 |
| 2017-01-31 00:00:00 |
| 2011-01-31 00:00:00 |
| 2007-01-31 00:00:00 |
Modifying the date with addMonths() and subMonths() will result in the following:
Command | Output |
|---|---|
| 2012-03-03 00:00:00 |
| 2017-01-31 00:00:00 |
| 2011-12-31 00:00:00 |
| 2007-01-31 00:00:00 |
Take note of how adding one month to “January 31” resulted in “March 3” instead of “February 28”. If you prefer to not have that rollover, you can use addMonthWithoutOverflow() and its related methods to avoid overflowing into the next month when the target month has fewer days.
Modifying the date with addDays() and subDays() will result in the following:
Command | Output |
|---|---|
| 2012-02-01 00:00:00 |
| 2012-02-29 00:00:00 |
| 2012-01-30 00:00:00 |
| 2012-01-02 00:00:00 |
Modifying the date with addWeekdays() and subWeekdays() will result in the following:
Command | Output |
|---|---|
| 2012-02-01 00:00:00 |
| 2012-02-06 00:00:00 |
| 2012-01-30 00:00:00 |
| 2012-01-25 00:00:00 |
Modifying the date with addWeeks() and subWeeks() will result in the following:
Command | Output |
|---|---|
| 2012-02-07 00:00:00 |
| 2012-02-21 00:00:00 |
| 2012-01-24 00:00:00 |
| 2012-01-10 00:00:00 |
Modifying the date with addHours() and subHours() will result in the following:
Command | Output |
|---|---|
| 2012-01-31 01:00:00 |
| 2012-02-01 00:00:00 |
| 2012-01-30 23:00:00 |
| 2012-01-30 00:00:00 |
Modifying the date with addMinutes() and subMinutes() will result in the following:
Command | Output |
|---|---|
| 2012-01-31 00:01:00 |
| 2012-01-31 01:01:00 |
| 2012-01-30 23:59:00 |
| 2012-01-30 22:59:00 |
Modifying the date with addSeconds() and subSeconds() will result in the following:
Command | Output |
|---|---|
| 2012-01-31 00:00:01 |
| 2012-01-31 00:01:01 |
| 2012-01-30 23:59:59 |
| 2012-01-30 23:58:59 |
Using Carbon’s add and subtract tools can provide you with adjusted date and times.
Another way to read or manipulate the time is to use Carbon’s getters and setters.
Read values with getters:
$dt = Carbon::now();
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);Change values with setters:
$dt = Carbon::now();
$dt->year = 2015;
$dt->month = 04;
$dt->day = 21;
$dt->hour = 22;
$dt->minute = 32;
$dt->second = 5;
echo $dt;We can even chain together some setters.
Here is the previous example using year(), month(), day(), hour(), minute(), and second():
$dt->year(2015)->month(4)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString();And here is the same example using setDate() and setTime():
$dt->setDate(2015, 4, 21)->setTime(22, 32, 5)->toDateTimeString();And here is the same example using setDateTime():
$dt->setDateTime(2015, 4, 21, 22, 32, 5)->toDateTimeString();All of these approaches will produce the same result: 2015-04-21 22:32:05.
PHP’s toXXXString() methods are available to display dates and times with predefined formatting:
Command | Output |
|---|---|
| 2015-04-21 |
| Apr 21, 2015 |
| 22:32:05 |
| 2015-04-21 22:32:05 |
| Tue, Apr 21, 2015 10:32 PM |
It’s also possible to use PHP’s DateTime format() for custom formatting:
echo $dt->format('l jS \of F Y h:i:s A');l: A full textual representation of the day of the week.jS:Day of the month without leading zeros.
English ordinal suffix for the day of the month, 2 characters.
F: A full textual representation of a month.Y: A full numeric representation of a year, 4 digits.h:i:s:12-hour format of an hour with leading zeros.
Minutes with leading zeros.
Seconds with leading zeros.
A: Uppercase Ante meridiem and Post meridiem.
This code will produce the following result:
OutputTuesday 21st of April 2015 10:32:05 PMUsing Carbon’s formatting tools can display dates and times to fit your needs.
Carbon also lets us display time relatively with the diff() methods.
For instance, let’s say we have a blog and wanted to show a published time of 3 hours ago. We would be able to do that with these methods.
Consider the following example with a time in the future and a time in the past:
$dt = Carbon::create(2012, 1, 31, 0);
$future = Carbon::create(2012, 1, 31, 0);
$past = Carbon::create(2012, 1, 31, 0);
$future = $future->addHours(6);
$past = $past->subHours(6);Here are the results using diffInHours():
Command | Output |
|---|---|
|
|
|
|
Consider the following example with a date in the future and a date in the past:
$dt = Carbon::create(2012, 1, 31, 0);
$future = Carbon::create(2012, 1, 31, 0);
$past = Carbon::create(2012, 1, 31, 0);
$future = $future->addMonth();
$past = $past->subMonths(2);Here are the results using diffInDays():
Command | Output |
|---|---|
|
|
|
|
Displaying time relatively can sometimes be more useful to readers than a date or timestamp.
For example, instead of displaying the time of a post like 8:12 AM, the time will be displayed as 3 hours ago.
The diffForHumans() method is used for calculating the difference and also converting it to a humanly readable format.
Consider the following example with a date in the future and a date in the past:
$dt = Carbon::create(2012, 1, 31, 0);
$future = Carbon::create(2012, 1, 31, 0);
$past = Carbon::create(2012, 1, 31, 0);
$future = $future->addMonth();
$past = $past->subMonth();Here are the results using diffForHumans():
Command | Output |
|---|---|
|
|
|
|
Laravel integrates Carbon directly into Eloquent models so that date attributes are returned as Carbon instances. This means you can call any Carbon method on fields like created_at, updated_at, or your own custom date fields.
By default, Eloquent treats created_at and updated_at as date attributes. For custom columns you can declare them in $casts to have them converted automatically:
class Subscription extends Model
{
protected $casts = [
'trial_ends_at' => 'datetime',
];
}With this cast in place, you can work with trial_ends_at as a Carbon instance:
$subscription = Subscription::find(1);
// trial_ends_at is a Carbon instance
if ($subscription->trial_ends_at->isPast()) {
// handle expired trial
}
// extend the trial by seven days
$subscription->trial_ends_at = $subscription->trial_ends_at->addDays(7);
$subscription->save();Laravel stores datetimes in the database as strings, but when you retrieve them on your models they are cast to Carbon. You can still customize the default date format for serialization using the $dateFormat property on the model if needed.
Under the hood, Carbon extends PHP’s DateTime class and adds a fluent, expressive API. Most projects prefer Carbon because it reduces boilerplate and makes chains of operations easier to read while still remaining compatible with existing DateTime based code.
One important design decision is mutability:
The
Carbonclass is mutable. Methods likeaddDays()andsubMonth()modify the instance in place and return$this.The
CarbonImmutableclass behaves like PHP’sDateTimeImmutable. Methods that change the date or time return a new instance and leave the original untouched.
For example:
use Carbon\Carbon;
use Carbon\CarbonImmutable;
$mutable = Carbon::create(2024, 1, 1);
$immutable = CarbonImmutable::create(2024, 1, 1);
$mutable->addDay(); // $mutable is now 2024-01-02
$newImmutable = $immutable->addDay(); // $immutable is still 2024-01-01In Laravel you can opt into immutable dates globally by changing the configuration in config/app.php with the date key, or locally by using CarbonImmutable in your own code where you want to avoid accidental mutations.
Working with time zones is a common source of bugs in web applications. Carbon makes it easier to adopt a consistent strategy:
Store all datetimes in the database in UTC.
Convert to a user’s local time zone only when displaying or interacting with times in the UI.
Avoid mixing naive and time zone aware datetimes in the same calculation.
You can create or convert Carbon instances with an explicit time zone:
// create a Carbon instance in UTC
$utc = Carbon::now('UTC');
// convert to a specific user's time zone
$userTime = $utc->copy()->setTimezone('America/New_York');In Laravel, you can control the default time zone via the timezone option in config/app.php. Carbon respects this configuration when you call helpers like now() or when Eloquent casts a database datetime column.
