PHP Carbon
last modified November 14, 2026
In this article, we show how to work with date and time in PHP with the Carbon
package. We use the nesbot/carbon package, version 3.
PHP Carbon
Carbon is a PHP datetime library. It extends the built-in PHP
DateTime class and adds a fluent API, easy parsing, human-readable
differences, and translations into many languages. Because a Carbon object
is a DateTime, it can be passed to any function that
accepts one.
The package provides two main classes. Carbon extends
DateTime and is mutable: methods such as addDay
modify the object. CarbonImmutable extends
DateTimeImmutable, and its methods return new objects. We show
the difference later in the article.
PHP Carbon setup
The package is installed with Composer. The Carbon 3 series requires PHP 8.1 or newer.
$ composer require nesbot/carbon
We install the nesbot/carbon package. The examples in this
article begin with the Composer autoloader and import the class with
use Carbon\Carbon.
Carbon now, today, yesterday and tomorrow
The following example shows how to get the current date and time and the dates around it.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$now = Carbon::now();
echo "Now: $now\n";
$today = Carbon::today();
echo "Today: $today\n";
$yesterday = Carbon::yesterday();
echo "Yesterday: $yesterday\n";
$tomorrow = Carbon::tomorrow();
echo "Tomorrow: $tomorrow\n";
echo 'Timezone: ', $now->tzName, "\n";
Carbon::now returns the current date and time.
Carbon::today, Carbon::yesterday and
Carbon::tomorrow return midnight of the respective day.
Carbon::setTestNow('2026-11-14 15:53:45');
The setTestNow method freezes the clock, so that
now and all relative expressions return the same time. It is
meant for tests, and we use it in this article to make the output reproducible.
In a real program, we would simply remove the line.
The tzName property is the name of the time zone. Carbon uses the
default time zone of PHP, which is UTC unless it is changed in
php.ini or with date_default_timezone_set.
$ php today.php Now: 2026-11-14 15:53:45 Today: 2026-11-14 00:00:00 Yesterday: 2026-11-13 00:00:00 Tomorrow: 2026-11-15 00:00:00 Timezone: UTC
Carbon create
Carbon instances can be created with several create methods.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
$d1 = Carbon::create(2026, 8, 25, 22, 48, 0);
echo $d1, "\n";
$d2 = Carbon::create(2026, 8, 25, 22, 48, 0, 'Europe/Moscow');
echo $d2, ' ', $d2->tzName, "\n";
$d3 = Carbon::createFromDate(2026, 8, 14, 'America/Chicago');
echo $d3->toDateString(), ' ', $d3->tzName, "\n";
$d4 = Carbon::createFromTime(14, 30, 15);
echo $d4->format('H:i:s'), "\n";
$d5 = Carbon::createFromTimestamp(1);
echo $d5, ' ', $d5->tzName, "\n";
$d6 = Carbon::createFromTimestamp(1, 'Europe/Bratislava');
echo $d6, ' ', $d6->tzName, "\n";
The example creates Carbon instances with six calls.
$d1 = Carbon::create(2026, 8, 25, 22, 48, 0);
The create method generates a Carbon instance from date and time
parts. Omitted parts default to zero.
$d2 = Carbon::create(2026, 8, 25, 22, 48, 0, 'Europe/Moscow');
In the second call, we also provide a time zone as the last argument.
$d3 = Carbon::createFromDate(2026, 8, 14, 'America/Chicago'); $d4 = Carbon::createFromTime(14, 30, 15);
With createFromDate, we set only the date parts; the time is the
current time. The createFromTime method works the other way round.
Therefore, we print only the part we have set.
$d5 = Carbon::createFromTimestamp(1); $d6 = Carbon::createFromTimestamp(1, 'Europe/Bratislava');
The createFromTimestamp method creates an instance from a Unix
timestamp. In Carbon 3, the result is in UTC unless we pass a time zone;
a Unix timestamp identifies the same instant everywhere, only its local
representation differs.
$ php create.php 2026-08-25 22:48:00 2026-08-25 22:48:00 Europe/Moscow 2026-08-14 America/Chicago 14:30:15 1970-01-01 00:00:01 +00:00 1970-01-01 01:00:01 Europe/Bratislava
Carbon parse and createFromFormat
The parse method understands most of the date formats that PHP's
strtotime understands. When the input has a fixed, known layout,
createFromFormat is more precise.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
$d1 = Carbon::parse('2026-05-06 16:45:00');
echo $d1, "\n";
$d2 = Carbon::parse('6 May 2026 4:45pm');
echo $d2, "\n";
$d3 = Carbon::createFromFormat('d/m/Y H:i', '06/05/2026 16:45');
echo $d3, "\n";
$d4 = Carbon::createFromFormat('Y-m-d H:i:s.u', '2026-05-06 16:45:00.613484');
echo $d4->format('Y-m-d H:i:s.u'), "\n";
echo "\nInvalid input\n";
try {
Carbon::parse('not a date');
} catch (InvalidFormatException $e) {
echo "parse() failed: ", get_class($e), "\n";
}
$rolled = Carbon::createFromFormat('Y-m-d', '2026-02-30');
echo 'createFromFormat() rolled over to ', $rolled->toDateString(), "\n";
function isValidDate(string $text): bool
{
$date = Carbon::createFromFormat('!Y-m-d', $text);
return $date !== null && $date->format('Y-m-d') === $text;
}
var_dump(isValidDate('2026-02-28'));
var_dump(isValidDate('2026-02-30'));
The first three calls create the same instant from three different notations.
The createFromFormat method takes a format string as the first
argument. The u character stands for microseconds.
Invalid text makes parse throw
InvalidFormatException. However, a well-formed but impossible
date such as February 30 does not raise an error; it rolls over to March 2, as
the underlying PHP DateTime does. If we need to validate user
input, we format the result back and compare it with the original text. The
leading ! in the format resets all fields that are not
mentioned in the format, so the time is midnight instead of the current time.
$ php parse.php 2026-05-06 16:45:00 2026-05-06 16:45:00 2026-05-06 16:45:00 2026-05-06 16:45:00.613484 Invalid input parse() failed: Carbon\Exceptions\InvalidFormatException createFromFormat() rolled over to 2026-03-02 bool(true) bool(false)
Carbon relative modifiers
Carbon instances can be created from relative expressions such as
next friday or 1 year ago.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
echo new Carbon('tomorrow'), "\n";
echo new Carbon('yesterday'), "\n";
echo new Carbon('next wednesday'), "\n";
echo new Carbon('last friday'), "\n";
echo new Carbon('this saturday'), "\n";
echo new Carbon('1 year ago'), "\n";
echo new Carbon('first day of next month'), "\n";
echo new Carbon('last day of this month'), "\n";
The example creates Carbon instances using several expressions. The current time is frozen at Saturday, November 14, 2026, 15:53:45.
Expressions that name a day, such as tomorrow,
next wednesday or this saturday, reset the time to
midnight, while expressions such as 1 year ago keep the time of
the day. Note that this saturday returns today when today is a
Saturday.
$ php relative_modifiers.php 2026-11-15 00:00:00 2026-11-13 00:00:00 2026-11-18 00:00:00 2026-11-13 00:00:00 2026-11-14 00:00:00 2025-11-14 15:53:45 2026-12-01 15:53:45 2026-11-30 15:53:45
Carbon next and previous
The next and previous methods give the next or
previous occurrence of the given day of the week.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$now = Carbon::now();
echo "$now ({$now->dayName})\n";
$next = $now->copy()->next(Carbon::MONDAY);
echo "Next Monday: $next\n";
$prev = $now->copy()->previous(Carbon::MONDAY);
echo "Previous Monday: $prev\n";
$next = $now->copy()->next('Saturday');
echo "Next Saturday: $next\n";
$first = $now->copy()->firstOfMonth(Carbon::FRIDAY);
echo "First Friday: $first\n";
The example shows the next and previous Monday and the next Saturday. The
firstOfMonth method returns the first occurrence of a given day of
the week in the month.
The next method never returns the current day; since today is
Saturday, the next Saturday is a week away. The returned time is midnight.
We work on a copy of the instance, because these methods modify the object.
$ php next_previous.php 2026-11-14 15:53:45 (Saturday) Next Monday: 2026-11-16 00:00:00 Previous Monday: 2026-11-09 00:00:00 Next Saturday: 2026-11-21 00:00:00 First Friday: 2026-11-06 00:00:00
Carbon datetime parts
A Carbon datetime consists of parts including year, month, day, or hour. They are available as properties.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$now = Carbon::now();
echo "year: {$now->year}\n";
echo "month: {$now->month} ({$now->monthName})\n";
echo "day: {$now->day}\n";
echo "hour: {$now->hour}\n";
echo "minute: {$now->minute}\n";
echo "second: {$now->second}\n";
echo "dayOfWeek: {$now->dayOfWeek} ({$now->dayName})\n";
echo "dayOfYear: {$now->dayOfYear}\n";
echo "weekOfYear: {$now->weekOfYear}\n";
echo "weekOfMonth: {$now->weekOfMonth}\n";
echo "daysInMonth: {$now->daysInMonth}\n";
echo "quarter: {$now->quarter}\n";
echo "timestamp: {$now->timestamp}\n";
echo "isLeapYear: ", var_export($now->isLeapYear(), true), "\n";
The example displays various parts of a Carbon datetime instance. The
dayOfWeek property is a number between 0 (Sunday) and 6
(Saturday), dayName and monthName are localized
names, and weekOfYear is the ISO-8601 week number.
$ php parts.php year: 2026 month: 11 (November) day: 14 hour: 15 minute: 53 second: 45 dayOfWeek: 6 (Saturday) dayOfYear: 318 weekOfYear: 46 weekOfMonth: 2 daysInMonth: 30 quarter: 4 timestamp: 1794671625 isLeapYear: false
Carbon setters and fluent API
Carbon also provides a convenient fluent API for modifying datetime values.
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $dt = Carbon::create(2026, 1, 1, 0, 0, 0); $dt->year(2026)->month(5)->day(6)->hour(16)->minute(12)->second(53); echo $dt, "\n"; $dt2 = Carbon::create(2026, 1, 1, 0, 0, 0); $dt2->setDate(2026, 5, 6)->setTime(16, 12, 53); echo $dt2, "\n"; $dt3 = Carbon::create(2026, 1, 1, 0, 0, 0); $dt3->setDateTime(2026, 5, 6, 16, 12, 53); echo $dt3, "\n"; $dt4 = Carbon::create(2026, 5, 6, 16, 12, 53); $dt4->month = 12; $dt4->hour = 8; echo $dt4, "\n";
The example sets the same datetime in four different ways: with chained
setter methods named after the parts, with setDate and
setTime, with setDateTime, and by assigning to
properties. Each setter returns the instance, so the calls can be chained.
$ php fluent_api.php 2026-05-06 16:12:53 2026-05-06 16:12:53 2026-05-06 16:12:53 2026-12-06 08:12:53
Carbon copy and CarbonImmutable
Carbon modification methods modify the instance. We can use the
copy method to work on a copy instead. Alternatively, we can use
the CarbonImmutable class, whose methods always return a new
object.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
use Carbon\CarbonImmutable;
Carbon::setTestNow('2026-11-14 15:53:45');
echo "Mutable Carbon\n";
$dt = Carbon::tomorrow();
echo $dt->subDay(), "\n";
echo $dt, "\n";
echo "\nCarbon with copy()\n";
$dt2 = Carbon::tomorrow();
echo $dt2->copy()->subDay(), "\n";
echo $dt2, "\n";
echo "\nCarbonImmutable\n";
$dt3 = CarbonImmutable::tomorrow();
echo $dt3->subDay(), "\n";
echo $dt3, "\n";
In the first case, subDay changes the original object, so both
lines print the same date. In the second case, copy creates a
clone, and the original instance remains intact. The immutable class
behaves in the same way without us having to remember to copy.
Mutation of shared objects is a common source of bugs, and many applications
prefer CarbonImmutable. The static method
Carbon::now() and friends are available in both classes.
$ php copy_method.php Mutable Carbon 2026-11-14 00:00:00 2026-11-14 00:00:00 Carbon with copy() 2026-11-14 00:00:00 2026-11-15 00:00:00 CarbonImmutable 2026-11-14 00:00:00 2026-11-15 00:00:00
Carbon addition and subtraction
Carbon provides a couple of different methods for easily adding and subtracting time.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$now = Carbon::now();
echo "$now\n";
echo $now->copy()->addDays(3), "\n";
echo $now->copy()->addHours(12), "\n";
echo $now->copy()->subDays(3), "\n";
echo $now->copy()->subHours(12), "\n";
echo $now->copy()->addWeeks(2), "\n";
echo $now->copy()->add(1, 'day')->add(30, 'minutes'), "\n";
The example presents the addDays, addHours,
subDays, subHours, and addWeeks
methods. The generic add method takes a value and a unit.
We call copy before each modification so that
$now stays the same.
$ php add_sub.php 2026-11-14 15:53:45 2026-11-17 15:53:45 2026-11-15 03:53:45 2026-11-11 15:53:45 2026-11-14 03:53:45 2026-11-28 15:53:45 2026-11-15 16:23:45
Carbon adding years, months and centuries
The following example shows other addition and subtraction methods.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$now = Carbon::now();
echo $now->copy()->addCenturies(2)->toDateString(), "\n";
echo $now->copy()->subCenturies(2)->toDateString(), "\n";
echo $now->copy()->addYears(2)->toDateString(), "\n";
echo $now->copy()->subYears(2)->toDateString(), "\n";
echo $now->copy()->addMonths(2)->toDateString(), "\n";
echo $now->copy()->subMonths(2)->toDateString(), "\n";
We show addCenturies, subCenturies,
addYears, subYears, addMonths,
and subMonths.
$ php add_sub_dates.php 2226-11-14 1826-11-14 2028-11-14 2024-11-14 2027-01-14 2026-09-14
Carbon month and year overflow
Adding a month to January 31 is ambiguous, because February has no 31st day.
By default, the surplus days overflow into the next month. The
NoOverflow variants clamp the result to the last day of the
month.
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $jan31 = Carbon::create(2026, 1, 31); echo 'addMonth(): ', $jan31->copy()->addMonth()->toDateString(), "\n"; echo 'addMonthNoOverflow(): ', $jan31->copy()->addMonthNoOverflow()->toDateString(), "\n"; $leap = Carbon::create(2024, 2, 29); echo 'addYear(): ', $leap->copy()->addYear()->toDateString(), "\n"; echo 'addYearNoOverflow(): ', $leap->copy()->addYearNoOverflow()->toDateString(), "\n";
Adding one month to January 31, 2026 gives "February 31", which overflows to
March 3 with addMonth (February 2026 has 28 days), but February 28 with
addMonthNoOverflow. The same holds for leap days; the year after
February 29, 2024 has no February 29.
When adding months in billing or subscription code, the
NoOverflow variants are usually the ones we want.
$ php overflow.php addMonth(): 2026-03-03 addMonthNoOverflow(): 2026-02-28 addYear(): 2025-03-01 addYearNoOverflow(): 2025-02-28
Carbon format datetime
Carbon provides several methods to format datetime.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$dt = Carbon::now();
echo $dt, "\n";
echo $dt->toDateTimeString(), "\n";
echo "******************************\n";
echo $dt->toDateString(), "\n";
echo $dt->toFormattedDateString(), "\n";
echo $dt->toTimeString(), "\n";
echo $dt->toDayDateTimeString(), "\n";
echo "******************************\n";
echo $dt->format('Y-m-d h:i:s A'), "\n";
echo $dt->format('l, jS \of F Y'), "\n";
The example provides basic formatting methods. When we print a Carbon object,
it is converted to the Y-m-d H:i:s format via the
__toString method. We can also generate our own format with
the format method, which accepts the same format characters as
the PHP date function.
$ php formatting.php 2026-11-14 15:53:45 2026-11-14 15:53:45 ****************************** 2026-11-14 Nov 14, 2026 15:53:45 Sat, Nov 14, 2026 3:53 PM ****************************** 2026-11-14 03:53:45 PM Saturday, 14th of November 2026
Carbon standard formats
The following example shows other common Carbon datetime formatting methods.
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $dt = Carbon::create(2026, 5, 6, 16, 45, 0, 'Europe/Bratislava'); echo $dt->toAtomString(), "\n"; echo $dt->toCookieString(), "\n"; echo $dt->toIso8601String(), "\n"; echo $dt->toIso8601ZuluString(), "\n"; echo $dt->toRfc822String(), "\n"; echo $dt->toRfc850String(), "\n"; echo $dt->toRfc1036String(), "\n"; echo $dt->toRfc1123String(), "\n"; echo $dt->toRfc3339String(), "\n"; echo $dt->toRfc7231String(), "\n"; echo $dt->toRssString(), "\n"; echo $dt->toW3cString(), "\n";
The example presents twelve methods that produce standard formats such as
ATOM, ISO 8601, RFC 822, RFC 3339, and RSS. We create the instance in the
Europe/Bratislava time zone, which was on UTC+2 on May 6; the
toIso8601ZuluString and toRfc7231String methods
convert the time to UTC.
$ php common_formats.php 2026-05-06T16:45:00+02:00 Wednesday, 06-May-2026 16:45:00 CEST 2026-05-06T16:45:00+02:00 2026-05-06T14:45:00Z Wed, 06 May 26 16:45:00 +0200 Wednesday, 06-May-26 16:45:00 CEST Wed, 06 May 26 16:45:00 +0200 Wed, 06 May 2026 16:45:00 +0200 2026-05-06T16:45:00+02:00 Wed, 06 May 2026 14:45:00 GMT Wed, 06 May 2026 16:45:00 +0200 2026-05-06T16:45:00+02:00
Carbon localized formatting
Carbon includes translations for more than 200 languages. The
translatedFormat method works like format, but
names of days and months are translated. The isoFormat method uses
the format tokens of Moment.js and offers localized shortcuts such as
LLLL.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
$dt = Carbon::create(2026, 5, 6, 16, 45, 0);
echo $dt->format('l j F Y'), "\n";
Carbon::setLocale('sk');
echo $dt->translatedFormat('l j. F Y'), "\n";
echo $dt->isoFormat('dddd D. MMMM YYYY'), "\n";
Carbon::setLocale('de');
echo $dt->isoFormat('dddd, D. MMMM YYYY'), "\n";
echo $dt->locale('fr')->isoFormat('LLLL'), "\n";
The setLocale method changes the default locale for all
subsequently created instances; the locale method changes the
locale of one object only. The last line uses the LLLL token,
which expands to the long date and time format of the locale.
$ php locale_format.php Wednesday 6 May 2026 streda 6. mája 2026 streda 6. mája 2026 Mittwoch, 6. Mai 2026 mercredi 6 mai 2026 16:45
Carbon compare datetime
Carbon has methods such as eq and gt for comparing
datetimes.
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $first = Carbon::create(2026, 5, 5, 22, 20, 1); $second = Carbon::create(2026, 5, 5, 20, 20, 1); echo $first, "\n"; echo $second, "\n"; var_dump($first->eq($second)); var_dump($first->ne($second)); var_dump($first->gt($second)); var_dump($first->gte($second)); var_dump($first->lt($second)); var_dump($first->lte($second)); var_dump($first->between($second, $first->copy()->addHour())); echo "Max: ", $first->max($second), "\n"; echo "Min: ", $first->min($second), "\n";
The example compares two datetime values. The eq,
ne, gt, gte, lt and
lte methods correspond to the comparison operators. The
between method tests whether a date lies between two others,
and max and min return the later and the earlier
instance.
Since Carbon objects are DateTime objects, we can also use the
standard operators ==, < and >.
$ php comparing.php 2026-05-05 22:20:01 2026-05-05 20:20:01 bool(false) bool(true) bool(true) bool(true) bool(false) bool(false) bool(true) Max: 2026-05-05 22:20:01 Min: 2026-05-05 20:20:01
Carbon predicates
Carbon has many is methods that test a date against the current
time or against the calendar.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
$dt = Carbon::create(2026, 11, 14, 9, 0, 0);
var_dump($dt->isToday());
var_dump($dt->isSaturday());
var_dump($dt->isWeekend());
var_dump($dt->isPast());
var_dump($dt->isFuture());
var_dump($dt->isSameMonth(Carbon::create(2026, 11, 1)));
var_dump($dt->isLeapYear());
var_dump(Carbon::tomorrow()->isFuture());
We test a datetime on Saturday, November 14, 2026, at 9:00, with the clock
frozen at 15:53:45 of the same day. The isToday,
isSaturday and isWeekend methods return true; the
isPast method is true because 9:00 is before 15:53;
isFuture is false. The methods isSameMonth and
isLeapYear test the calendar.
$ php predicates.php bool(true) bool(true) bool(true) bool(true) bool(false) bool(true) bool(false) bool(true)
Carbon datetime difference
The diffInDays, diffInHours and similar methods
compute the difference between two dates.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
$start = Carbon::create(2026, 1, 1, 8, 0, 0);
$end = Carbon::create(2026, 3, 15, 20, 30, 0);
echo 'days: ', $start->diffInDays($end), "\n";
echo 'whole days: ', (int) $start->diffInDays($end), "\n";
echo 'weeks: ', $start->diffInWeeks($end), "\n";
echo 'months: ', $start->diffInMonths($end), "\n";
echo 'hours: ', $start->diffInHours($end), "\n";
echo 'minutes: ', $start->diffInMinutes($end), "\n";
echo "\nReversed:\n";
echo 'days: ', $end->diffInDays($start), "\n";
echo 'absolute: ', $end->diffInDays($start, true), "\n";
$diff = $start->diff($end);
echo "\n{$diff->m} months, {$diff->d} days, {$diff->h} hours, {$diff->i} minutes\n";
Starting with Carbon 3, these methods return a float that
includes the fractional part, and the result is signed: it is negative
when the other date is earlier. To get the absolute value, we pass
true as the second argument; to get whole days, we cast the result
to int.
The diff method returns a DateInterval with
the individual components, so we can print "2 months, 14 days, ...". Code written
for Carbon 2, which returned positive whole numbers, may need adjusting when
it is upgraded.
$ php diff.php days: 73.520833333333 whole days: 73 weeks: 10.502976190476 months: 2.4684139784946 hours: 1764.5 minutes: 105870 Reversed: days: -73.520833333333 absolute: 73.520833333333 2 months, 14 days, 12 hours, 30 minutes
Carbon humanized datetime difference
Applications often show datetime differences in a so called humanized format; e.g. in one year or 3 minutes ago.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
Carbon::setTestNow('2026-11-14 15:53:45');
echo Carbon::now()->addYear()->diffForHumans(), "\n";
echo Carbon::now()->subDays(3)->diffForHumans(), "\n";
echo Carbon::now()->subMinutes(45)->diffForHumans(), "\n";
echo Carbon::now()->addHours(5)->diffForHumans(['parts' => 2]), "\n";
echo Carbon::now()->subDays(3)->diffForHumans(null, true), "\n";
Carbon::setLocale('de');
echo Carbon::now()->addYear()->diffForHumans(), "\n";
Carbon::setLocale('sk');
echo Carbon::now()->addYear()->diffForHumans(), "\n";
echo Carbon::now()->locale('hu')->subDays(3)->diffForHumans(), "\n";
The diffForHumans method compares the instance with the current
time (here frozen with setTestNow). The parts option
controls how many units are shown, and passing null, true removes
the "ago" and "from now" words. The last three calls show the result in
German, Slovak and Hungarian locales.
$ php humanized.php 1 year from now 3 days ago 45 minutes ago 5 hours from now 3 days in 1 Jahr o 1 rok 3 napja
Carbon time zones and UTC
Coordinated Universal Time (UTC) is the primary time standard by which the world regulates clocks and time. Carbon offers methods to convert between time zones.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
$dt = Carbon::create(2026, 7, 13, 15, 59, 49, 'Europe/Bratislava');
echo $dt, ' ', $dt->tzName, "\n";
echo 'Offset hours: ', $dt->offsetHours, "\n";
echo 'Is UTC: ', var_export($dt->isUtc(), true), "\n";
echo "******************************\n";
$utc = $dt->copy()->utc();
echo $utc, ' ', $utc->tzName, "\n";
echo 'Is UTC: ', var_export($utc->isUtc(), true), "\n";
echo "******************************\n";
$ny = $dt->copy()->setTimezone('America/New_York');
echo $ny, ' ', $ny->tzName, "\n";
var_dump($dt->eq($ny));
$shifted = $dt->copy()->shiftTimezone('Asia/Tokyo');
echo $shifted, ' ', $shifted->tzName, "\n";
The example creates a datetime in Bratislava and prints its time zone
name and offset in hours. The isUtc method tells us whether
the time zone is UTC.
The utc and setTimezone methods convert the instant to
another time zone; the moment in time stays the same, which is why
eq returns true. The shiftTimezone method keeps the
wall-clock time and changes the zone, which describes a different moment.
$ php utc.php 2026-07-13 15:59:49 Europe/Bratislava Offset hours: 2 Is UTC: false ****************************** 2026-07-13 13:59:49 UTC Is UTC: true ****************************** 2026-07-13 09:59:49 America/New_York bool(true) 2026-07-13 15:59:49 Asia/Tokyo
Carbon modifiers
Modifier methods perform helpful modifications to the current instance. They can retrieve the start or end of a day, week, month, or year.
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use Carbon\Carbon; $dt = Carbon::create(2026, 11, 14, 15, 53, 45); echo "Start/End of day\n"; echo $dt->copy()->startOfDay(), "\n"; echo $dt->copy()->endOfDay(), "\n"; echo "\nStart/End of week\n"; echo $dt->copy()->startOfWeek(), "\n"; echo $dt->copy()->endOfWeek(), "\n"; echo "\nStart/End of month\n"; echo $dt->copy()->startOfMonth(), "\n"; echo $dt->copy()->endOfMonth(), "\n"; echo "\nStart/End of year\n"; echo $dt->copy()->startOfYear(), "\n"; echo $dt->copy()->endOfYear(), "\n"; echo "\nStart/End of decade\n"; echo $dt->copy()->startOfDecade(), "\n"; echo $dt->copy()->endOfDecade(), "\n"; echo "\nStart/End of century\n"; echo $dt->copy()->startOfCentury(), "\n"; echo $dt->copy()->endOfCentury(), "\n";
The example presents a couple of modifiers. By default, the week starts on Monday and ends on Sunday. The end of a period is set to 23:59:59.999999.
$ php modifiers.php Start/End of day 2026-11-14 00:00:00 2026-11-14 23:59:59 Start/End of week 2026-11-09 00:00:00 2026-11-15 23:59:59 Start/End of month 2026-11-01 00:00:00 2026-11-30 23:59:59 Start/End of year 2026-01-01 00:00:00 2026-12-31 23:59:59 Start/End of decade 2020-01-01 00:00:00 2029-12-31 23:59:59 Start/End of century 2001-01-01 00:00:00 2100-12-31 23:59:59
Carbon periods and intervals
The CarbonPeriod class iterates over a range of dates, and the
CarbonInterval class represents a length of time.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;
$period = CarbonPeriod::create('2026-11-09', '2026-11-15');
foreach ($period as $date) {
echo $date->format('D, d M'), "\n";
}
echo "\nEvery 2 days:\n";
$period = CarbonPeriod::create('2026-11-01', '2 days', '2026-11-10');
foreach ($period as $date) {
echo $date->toDateString(), "\n";
}
echo "\nWorking days:\n";
$period = CarbonPeriod::create('2026-11-09', '2026-11-15')
->filter(fn (Carbon $date) => $date->isWeekday());
foreach ($period as $date) {
echo $date->format('l'), "\n";
}
echo "\nnumber of days: ", CarbonPeriod::create('2026-01-01', '2026-12-31')->count(), "\n";
$interval = CarbonInterval::hours(2)->minutes(30);
echo "\nInterval: $interval\n";
echo 'Total minutes: ', $interval->totalMinutes, "\n";
echo Carbon::create(2026, 11, 14, 10)->add($interval), "\n";
We create a period by passing the start and the end date. We can add a step
such as 2 days as the second argument, and filter the dates with a
callback; here we keep only the weekdays. The count method returns
the number of dates in the period.
The CarbonInterval::hours(2)->minutes(30) expression creates an
interval of two and a half hours. It can be added to a date and it provides
totals such as totalMinutes.
$ php periods.php Mon, 09 Nov Tue, 10 Nov Wed, 11 Nov Thu, 12 Nov Fri, 13 Nov Sat, 14 Nov Sun, 15 Nov Every 2 days: 2026-11-01 2026-11-03 2026-11-05 2026-11-07 2026-11-09 Working days: Monday Tuesday Wednesday Thursday Friday number of days: 365 Interval: 2 hours 30 minutes Total minutes: 150 2026-11-14 12:30:00
Source
In this article, we have used PHP Carbon to create, parse, format, compare and modify dates and times. For the built-in classes behind it, see the PHP DateTime tutorial. Another way to install packages is described in PHP Composer and autoloading.
Author
List all PHP tutorials.