Introduction

The Carbon class is inherited from the PHP DateTime class.

<?php
namespace Carbon;

class Carbon extends \DateTime
{
    // code here
}

You can see from the code snippet above that the Carbon class is declared in the Carbon namespace. You need to import the namespace to use Carbon without having to provide its fully qualified name each time.

use Carbon\Carbon;

Examples in this documentation will assume you imported classes of the Carbon namespace this way.

We also provide CarbonImmutable class extending DateTimeImmutable. The same methods are available on both classes but when you use a modifier on a Carbon instance, it modifies and returns the same instance, when you use it on CarbonImmutable, it returns a new instances with the new value.

$mutable = Carbon::now();
$immutable = CarbonImmutable::now();
$modifiedMutable = $mutable->add(1, 'day');
$modifiedImmutable = CarbonImmutable::now()->add(1, 'day');

var_dump($modifiedMutable === $mutable);             // bool(true)
var_dump($mutable->isoFormat('dddd D'));             // string(11) "Saturday 10"
var_dump($modifiedMutable->isoFormat('dddd D'));     // string(11) "Saturday 10"
// So it means $mutable and $modifiedMutable are the same object
// both set to now + 1 day.
var_dump($modifiedImmutable === $immutable);         // bool(false)
var_dump($immutable->isoFormat('dddd D'));           // string(8) "Friday 9"
var_dump($modifiedImmutable->isoFormat('dddd D'));   // string(11) "Saturday 10"
// While $immutable is still set to now and cannot be changed and
// $modifiedImmutable is a new instance created from $immutable
// set to now + 1 day.

$mutable = CarbonImmutable::now()->toMutable();
var_dump($mutable->isMutable());                     // bool(true)
var_dump($mutable->isImmutable());                   // bool(false)
$immutable = Carbon::now()->toImmutable();
var_dump($immutable->isMutable());                   // bool(false)
var_dump($immutable->isImmutable());                 // bool(true)

The library also provides CarbonInterface interface extends DateTimeInterface and JsonSerializable, CarbonInterval class extends DateInterval, CarbonTimeZone class extends DateTimeZone and CarbonPeriod class polyfills DatePeriod.

Carbon has all of the functions inherited from the base DateTime class. This approach allows you to access the base functionality such as modify, format or diff.

Now, let see how cool is this doc. Click on the code below:

$dtToronto = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Toronto');
$dtVancouver = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Vancouver');
// Try to replace the 4th number (hours) or the last argument (timezone) with
// Europe/Paris for example and see the actual result on the right hand.
// It's alive!

echo $dtVancouver->diffInHours($dtToronto); // 3
// Now, try to double-click on "diffInHours" or "create" to open
// the References panel.
// Once the references panel is open, you can use the search field to
// filter the list or click the (<) button to close it.

Some examples are static snippets, some other are editable (when there is a top right hand corner expand button). You can also click on this button to open the snippet in a new tab. You can double-click on methods name in both static and dynamic examples.

Instantiation

There are several different methods available to create a new instance of Carbon. First there is a constructor. It overrides the parent constructor and you are best to read about the first parameter from the PHP manual and understand the date/time string formats it accepts. You'll hopefully find yourself rarely using the constructor but rather relying on the explicit static methods for improved readability.

$carbon = new Carbon();                  // equivalent to Carbon::now()
$carbon = new Carbon('first day of January 2008', 'America/Vancouver');
echo get_class($carbon);                 // 'Carbon\Carbon'

You'll notice above that the timezone (2nd) parameter was passed as a string rather than a \DateTimeZone instance. All DateTimeZone parameters have been augmented so you can pass a DateTimeZone instance, string or integer offset to GMT and the timezone will be created for you. This is again shown in the next example which also introduces the now() function.

$now = Carbon::now(); // will use timezone as set with date_default_timezone_set
// PS: we recommend you to work with UTC as default timezone and only use
// other timezones (such as the user timezone) on display

$nowInLondonTz = Carbon::now(new DateTimeZone('Europe/London'));

// or just pass the timezone as a string
$nowInLondonTz = Carbon::now('Europe/London');
echo $nowInLondonTz->tzName;             // Europe/London
echo "\n";

// or to create a date with a custom fixed timezone offset
$date = Carbon::now('+13:30');
echo $date->tzName;                      // +13:30
echo "\n";

// Get/set minutes offset from UTC
echo $date->utcOffset();                 // 810
echo "\n";

$date->utcOffset(180);

echo $date->tzName;                      // +03:00
echo "\n";
echo $date->utcOffset();                 // 180

If you really love your fluid method calls and get frustrated by the extra line or ugly pair of brackets necessary when using the constructor you'll enjoy the parse method.

echo (new Carbon('first day of December 2008'))->addWeeks(2);     // 2008-12-15 00:00:00
echo "\n";
echo Carbon::parse('first day of December 2008')->addWeeks(2);    // 2008-12-15 00:00:00

The string passed to Carbon::parse or to new Carbon can represent a relative time (next sunday, tomorrow, first day of next month, last year) or an absolute time (first day of December 2008, 2017-01-06). You can test if a string will produce a relative or absolute date with Carbon::hasRelativeKeywords().

$string = 'first day of next month';
if (strtotime($string) === false) {
    echo "'$string' is not a valid date/time string.";
} elseif (Carbon::hasRelativeKeywords($string)) {
    echo "'$string' is a relative valid date/time string, it will returns different dates depending on the current date.";
} else {
    echo "'$string' is an absolute date/time string, it will always returns the same date.";
}

To accompany now(), a few other static instantiation helpers exist to create widely known instances. The only thing to really notice here is that today(), tomorrow() and yesterday(), besides behaving as expected, all accept a timezone parameter and each has their time value set to 00:00:00.

$now = Carbon::now();
echo $now;                               // 2019-08-09 15:17:13
echo "\n";
$today = Carbon::today();
echo $today;                             // 2019-08-09 00:00:00
echo "\n";
$tomorrow = Carbon::tomorrow('Europe/London');
echo $tomorrow;                          // 2019-08-10 00:00:00
echo "\n";
$yesterday = Carbon::yesterday();
echo $yesterday;                         // 2019-08-08 00:00:00

The next group of static helpers are the createXXX() helpers. Most of the static create functions allow you to provide as many or as few arguments as you want and will provide default values for all others. Generally default values are the current date, time or timezone. Higher values will wrap appropriately but invalid values will throw an InvalidArgumentException with an informative message. The message is obtained from an DateTime::getLastErrors() call.

$year = 2000; $month = 4; $day = 19;
$hour = 20; $minute = 30; $second = 15; $tz = 'Europe/Madrid';
echo Carbon::createFromDate($year, $month, $day, $tz)."\n";
echo Carbon::createMidnightDate($year, $month, $day, $tz)."\n";
echo Carbon::createFromTime($hour, $minute, $second, $tz)."\n";
echo Carbon::createFromTimeString("$hour:$minute:$second", $tz)."\n";
echo Carbon::create($year, $month, $day, $hour, $minute, $second, $tz)."\n";

createFromDate() will default the time to now. createFromTime() will default the date to today. create() will default any null parameter to the current respective value. As before, the $tz defaults to the current timezone and otherwise can be a DateTimeZone instance or simply a string timezone value. The only special case is for create() that has minimum value as default for missing argument but default on current value when you pass explicitly null.

$xmasThisYear = Carbon::createFromDate(null, 12, 25);  // Year defaults to current year
$Y2K = Carbon::create(2000, 1, 1, 0, 0, 0); // equivalent to Carbon::createMidnightDate(2000, 1, 1)
$alsoY2K = Carbon::create(1999, 12, 31, 24);
$noonLondonTz = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$teaTime = Carbon::createFromTimeString('17:00:00', 'Europe/London');

try { Carbon::create(1975, 5, 21, 22, -2, 0); } catch(InvalidArgumentException $x) { echo $x->getMessage(); }
// minute must be between 0 and 99, -2 given

// Be careful, as Carbon::createFromDate() default values to current date, it can trigger overflow:
// For example, if we are the 15th of June 2020, the following will set the date on 15:
Carbon::createFromDate(2019, 4); // 2019-04-15
// If we are the 31th of October, as 31th April does not exist, it overflows to May:
Carbon::createFromDate(2019, 4); // 2019-05-01
// That's why you simply should not use Carbon::createFromDate() with only 2 parameters (1 or 3 are safe, but no 2)

Create exceptions occurs on such negative values but not on overflow, to get exceptions on overflow, use createSafe()

echo Carbon::create(2000, 1, 35, 13, 0, 0);
// 2000-02-04 13:00:00
echo "\n";

try {
    Carbon::createSafe(2000, 1, 35, 13, 0, 0);
} catch (\Carbon\Exceptions\InvalidDateException $exp) {
    echo $exp->getMessage();
}
// day : 35 is not a valid value.

Note 1: 2018-02-29 produces also an exception while 2020-02-29 does not since 2020 is a leap year.

Note 2: Carbon::createSafe(2014, 3, 30, 1, 30, 0, 'Europe/London') also produces an exception as this time is in an hour skipped by the daylight saving time.

Note 3: The PHP native API allow consider there is a year 0 between -1 and 1 even if it doesn't regarding to Gregorian calendar. That's why years lower than 1 will throw an exception using createSafe. Check isValid() for year-0 detection.

Carbon::createFromFormat($format, $time, $tz);

createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat. The difference being again the $tz argument can be a DateTimeZone instance or a string timezone value. Also, if there are errors with the format this function will call the DateTime::getLastErrors() method and then throw a InvalidArgumentException with the errors as the message.

echo Carbon::createFromFormat('Y-m-d H', '1975-05-21 22')->toDateTimeString(); // 1975-05-21 22:00:00

The final three create functions are for working with unix timestamps. The first will create a Carbon instance equal to the given timestamp and will set the timezone as well or default it to the current timezone. The second, createFromTimestampUTC(), is different in that the timezone will remain UTC (GMT), it acts the same as Carbon::parse('@'.$timestamp) but I have just made it a little more explicit. The third, createFromTimestampMs(), accepts a timestamp in milliseconds instead of seconds. Negative timestamps are also allowed.

echo Carbon::createFromTimestamp(-1)->toDateTimeString();                                  // 1969-12-31 23:59:59
echo Carbon::createFromTimestamp(-1, 'Europe/London')->toDateTimeString();                 // 1970-01-01 00:59:59
echo Carbon::createFromTimestampUTC(-1)->toDateTimeString();                               // 1969-12-31 23:59:59
echo Carbon::createFromTimestampMs(1)->format('Y-m-d\TH:i:s.uP T');                        // 1970-01-01T00:00:00.001000+00:00 UTC
echo Carbon::createFromTimestampMs(1, 'Europe/London')->format('Y-m-d\TH:i:s.uP T');       // 1970-01-01T01:00:00.001000+01:00 BST

You can also create a copy() of an existing Carbon instance. As expected the date, time and timezone values are all copied to the new instance.

$dt = Carbon::now();
echo $dt->diffInYears($dt->copy()->addYear());  // 1

// $dt was unchanged and still holds the value of Carbon:now()

You can use nowWithSameTz() on an existing Carbon instance to get a new instance at now in the same timezone.

$meeting = Carbon::createFromTime(19, 15, 00, 'Africa/Johannesburg');

// 19:15 in Johannesburg
echo 'Meeting starts at '.$meeting->format('H:i').' in Johannesburg.';                  // Meeting starts at 19:15 in Johannesburg.
// now in Johannesburg
echo "It's ".$meeting->nowWithSameTz()->format('H:i').' right now in Johannesburg.';    // It's 17:17 right now in Johannesburg.

Finally, if you find yourself inheriting a \DateTime instance from another library, fear not! You can create a Carbon instance via a friendly instance() method. Or use the even more flexible method make() which can return a new Carbon instance from a DateTime, Carbon or from a string, else it just returns null.

$dt = new \DateTime('first day of January 2008'); // <== instance from another API
$carbon = Carbon::instance($dt);
echo get_class($carbon);                               // 'Carbon\Carbon'
echo $carbon->toDateTimeString();                      // 2008-01-01 00:00:00

Carbon 2 (requiring PHP >= 7.1) perfectly supports microseconds. But if you use Carbon 1 and PHP < 7.1, read our section about partial microseconds support.

Before PHP 7.1 DateTime microseconds are not added to "now" instances and cannot be changed afterwards, this means:

$date = new DateTime('now');
echo $date->format('u');
// display current microtime in PHP >= 7.1 (expect a bug in PHP 7.1.3 only)
// display 000000 before PHP 7.1

$date = new DateTime('2001-01-01T00:00:00.123456Z');
echo $date->format('u');
// display 123456 in all PHP versions

$date->modify('00:00:00.987654');
echo $date->format('u');
// display 987654 in PHP >= 7.1
// display 123456 before PHP 7.1

To work around this limitation in Carbon, we append microseconds when calling now in PHP < 7.1, but this feature can be disabled on demand (no effect in PHP >= 7.1):

Carbon::useMicrosecondsFallback(false);
var_dump(Carbon::isMicrosecondsFallbackEnabled()); // false

echo Carbon::now()->micro; // 0 in PHP < 7.1, microtime in PHP >= 7.1

Carbon::useMicrosecondsFallback(true); // default value
var_dump(Carbon::isMicrosecondsFallbackEnabled()); // true

echo Carbon::now()->micro; // microtime in all PHP version

Ever need to loop through some dates to find the earliest or latest date? Didn't know what to set your initial maximum/minimum values to? There are now two helpers for this to make your decision simple:

echo Carbon::maxValue();                               // '9999-12-31 23:59:59'
echo Carbon::minValue();                               // '0001-01-01 00:00:00'

Min and max value mainly depends on the system (32 or 64 bit).

With a 32-bit OS system or 32-bit version of PHP (you can check it in PHP with PHP_INT_SIZE === 4), the minimum value is the 0-unix-timestamp (1970-01-01 00:00:00) and the maximum is the timestamp given by the constant PHP_INT_MAX.

With a 64-bit OS system and 64-bit version of PHP, the minimum is 01-01-01 00:00:00 and maximum is 9999-12-31 23:59:59. It's even possible to use negative year up to -9999 but be aware you may not have accurate results with some operations as the year 0 exists in PHP but not in the Gregorian calendar.

Localization

With Carbon 2, localization changed a lot, 750 new locales are supported and we now embed locale formats, day names, month names, ordinal suffixes, meridiem, week start and more. While Carbon 1 provided partial support and relied on third-party like IntlDateFormatter class and language packages for advanced translation, you now benefit of a wide internationalization support. You still use Carbon 1? I hope you would consider to upgrade, version 2 has really cool new features. Else you still read the version 1 documentation of Localization by clicking here.

Unfortunately the base class DateTime does not have any localization support. To begin localization support a formatLocalized($format) method was added. The implementation makes a call to strftime using the current instance timestamp. If you first set the current locale with PHP function setlocale() then the string returned will be formatted in the correct locale.

$newLocale = setlocale(LC_TIME, 'German');
$dt = Carbon::parse('1975-05-21 22:23:00.123456');
if ($newLocale === false) {
    echo '"German" locale is not installed on your machine, it may have a different name on your machine or you may need to install it.';
}
echo $dt->formatLocalized('%A %d %B %Y');          // Mittwoch 21 Mai 1975
setlocale(LC_TIME, 'English');
echo $dt->formatLocalized('%A %d %B %Y');          // Wednesday 21 May 1975
setlocale(LC_TIME, ''); // reset locale

diffForHumans() has also been localized. You can set the Carbon locale by using the static Carbon::setLocale() function and get the current setting with Carbon::getLocale().

Carbon::setLocale('de');
echo Carbon::getLocale();                          // de
echo Carbon::now()->addYear()->diffForHumans();    // in 11 Monaten

Carbon::setLocale('en');
echo Carbon::getLocale();                          // en

Or you can isolate some code with a given locale:

Carbon::executeWithLocale('de', function ($newLocale) {
    // You can optionally get $newLocale as the first argument of the closure
    // It will be set to the new locale or false if the locale was not found.

    echo Carbon::now()->addYear()->diffForHumans();
}); // in 11 Monaten

// outside the function the locale did not change
echo Carbon::getLocale();                          // en

// or same using a return statement
$french = Carbon::executeWithLocale('fr', function () {
    return Carbon::now()->addYear()->diffForHumans();
});
echo $french; // dans 11 mois

Some languages require utf8 encoding to be printed (locale packages that does not ends with .UTF8 mainly). In this case you can use the static method Carbon::setUtf8() to encode the result of the formatLocalized() call to the utf8 charset.

setlocale(LC_TIME, 'Spanish');
$dt = Carbon::create(2016, 01, 06, 00, 00, 00);
Carbon::setUtf8(false);
echo $dt->formatLocalized('%A %d %B %Y');          // miιrcoles 06 enero 2016
Carbon::setUtf8(true);
echo $dt->formatLocalized('%A %d %B %Y');          // miΓ©rcoles 06 enero 2016
Carbon::setUtf8(false);
setlocale(LC_TIME, '');

on Linux
If you have trouble with translations, check locales installed in your system (local and production).
locale -a to list locales enabled.
sudo locale-gen fr_FR.UTF-8 to install a new locale.
sudo dpkg-reconfigure locales to publish all locale enabled.
And reboot your system.

Since 2.9.0, you can easily customize translations:

// we recommend to use custom language name/variant
// rather than overriding an existing language
// to avoid conflict such as "en_Boring" in the example below:
$boringLanguage = 'en_Boring';
$translator = \Carbon\Translator::get($boringLanguage);
$translator->setTranslations([
    'day' => ':count boring day|:count boring days',
]);
// as this language starts with "en_" it will inherit from the locale "en"

$date1 = Carbon::create(2018, 1, 1, 0, 0, 0);
$date2 = Carbon::create(2018, 1, 4, 4, 0, 0);

echo $date1->locale($boringLanguage)->diffForHumans($date2); // 3 boring days before

$translator->setTranslations([
    'before' => function ($time) {
        return '['.strtoupper($time).']';
    },
]);

echo $date1->locale($boringLanguage)->diffForHumans($date2); // [3 BORING DAYS]

You can use fallback locales by passing in order multiple ones to locale():

\Carbon\Translator::get('xx')->setTranslations([
    'day' => ':count Xday',
]);
\Carbon\Translator::get('xy')->setTranslations([
    'day' => ':count Yday',
    'hour' => ':count Yhour',
]);

$date = Carbon::now()->locale('xx', 'xy', 'es')->sub('3 days 6 hours 40 minutes');

echo $date->ago(['parts' => 3]); // hace 3 Xday 6 Yhour 40 minutos

In the example above, it will try to find translations in "xx" in priority, then in "xy" if missing, then in "es", so here, you get "Xday" from "xx", "Yday" from "xy", and "hace" and "minutos" from "es".

Note that you can also use an other translator with Carbon::setTranslator($custom) as long as the given translator implements Symfony\Component\Translation\TranslatorInterface. And you can get the global default translator using Carbon::getTranslator() (and Carbon::setFallbackLocale($custom) and Carbon::getFallbackLocale() for the fallback locale, setFallbackLocale can be called multiple times to get multiple fallback locales) but as those method will change the behavior globally (including third-party libraries you may have in your app), it might cause unexpected results. You should rather customize translation using custom locales as in the example above.

Carbon embed a default translator that extends Symfony\Component\Translation\Translator You can check here the methods we added to it.

The Carbon translator will use internal directory src/Carbon/Lang to find translations files in it by default but you can change/add/remove directory.

$translator = Translator::get('en');
$directories = $translator->getDirectories();
var_dump($directories); // Check actual directory

// Change the whole list
$translator->setDirectories([
    'corporate/translations',
    'users/translations',
]);
// Add one directory to the list
$translator->addDirectory('external/translations/directory');
// Remove one directory from the list
$translator->removeDirectory('users/translations');

// After such a settings change, you could need to clear the cache with `resetMessages`
$translator->resetMessages();

// To restore the initial settings simply recall setDirectories with the original list:
$translator->setDirectories($directories);

Then you can find all language files across those directories.

$translator = Translator::get();
var_dump($translator->getLocalesFiles()); // /path/to/af.php, /path/to/ar.php, etc.
var_dump($translator->getAvailableLocales()); // af, ar, etc.

// You can also filter files/locales starting with a given prefix:
echo implode(', ', array_map('basename', $translator->getLocalesFiles('fr'))); // fr.php, fr_BE.php, fr_BF.php, fr_BI.php, fr_BJ.php, fr_BL.php, fr_CA.php, fr_CD.php, fr_CF.php, fr_CG.php, fr_CH.php, fr_CI.php, fr_CM.php, fr_DJ.php, fr_DZ.php, fr_FR.php, fr_GA.php, fr_GF.php, fr_GN.php, fr_GP.php, fr_GQ.php, fr_HT.php, fr_KM.php, fr_LU.php, fr_MA.php, fr_MC.php, fr_MF.php, fr_MG.php, fr_ML.php, fr_MQ.php, fr_MR.php, fr_MU.php, fr_NC.php, fr_NE.php, fr_PF.php, fr_PM.php, fr_RE.php, fr_RW.php, fr_SC.php, fr_SN.php, fr_SY.php, fr_TD.php, fr_TG.php, fr_TN.php, fr_VU.php, fr_WF.php, fr_YT.php
echo implode(', ', $translator->getAvailableLocales('fr')); // fr, fr_BE, fr_BF, fr_BI, fr_BJ, fr_BL, fr_CA, fr_CD, fr_CF, fr_CG, fr_CH, fr_CI, fr_CM, fr_DJ, fr_DZ, fr_FR, fr_GA, fr_GF, fr_GN, fr_GP, fr_GQ, fr_HT, fr_KM, fr_LU, fr_MA, fr_MC, fr_MF, fr_MG, fr_ML, fr_MQ, fr_MR, fr_MU, fr_NC, fr_NE, fr_PF, fr_PM, fr_RE, fr_RW, fr_SC, fr_SN, fr_SY, fr_TD, fr_TG, fr_TN, fr_VU, fr_WF, fr_YT

You can access some dynamic properties translated by calling following methods with the name of the base property.

$date = Carbon::parse('2018-02-25 14:00');
echo $date->locale('af_ZA')->meridiem();                     // NM
echo "\n";
echo $date->locale('af_ZA')->meridiem(true);                 // nm
echo "\n";
// Some languages has alternative numbers available:
echo $date->locale('ja_JP')->translateNumber(45);            // 四十五
echo "\n";
// You can also choose a key linked to a numeric value to translate:
echo $date->locale('ja_JP')->getAltNumber('day');            // δΊŒεδΊ”
// Note: translations methods like translateNumber and getAltNumber are available
// on CarbonInterval and CarbonPeriod too.
echo "\n";
echo $date->locale('en_SG')->ordinal('day');                 // 25th
echo "\n";
// As ordinal can be gender specific or have context dependency, you can pass the period format as second argument:
$date = Carbon::parse('2018-01-01 14:00');
echo $date->locale('fr_CH')->ordinal('isoWeek', 'w');        // 1re
echo "\n";
echo $date->locale('fr_CH')->ordinal('day', 'd');            // 1er
echo "\n";

Finally, you can get and set messages from the internal cache:

$translator = Translator::get('en');
echo Carbon::now()->addSeconds(312)->setLocalTranslator($translator)->diffForHumans(); // 5 minutes from now
echo "\n";

// Below, setMessages will load the english file(s) if available and if not yet loaded in cache, then will change the
// 'from_now' translation
$translator->setMessages('en', [
    'from_now' => 'in :time',
]);
echo Carbon::now()->addSeconds(312)->setLocalTranslator($translator)->diffForHumans(); // in 5 minutes
echo "\n";
echo $translator->getMessages('en')['from_now']; // in :time

setMessages is equivalent to setTranslations but you can omit the locale as it will use the current one so we recommend to use it when you can as in this previous example.

So the support of a locale for formatLocalized, getters such as localeMonth, localeDayOfWeek and short variants is driven by locales installed in your operating system. For other translations, it's supported internally thanks to Carbon community. You can check what's supported with the following methods:

echo implode(', ', array_slice(Carbon::getAvailableLocales(), 0, 3)).'...';      // aa, aa_DJ, aa_ER...

// Support diff syntax (before, after, from now, ago)
var_dump(Carbon::localeHasDiffSyntax('en'));                                     // bool(true)
var_dump(Carbon::localeHasDiffSyntax('zh_TW'));                                  // bool(true)
// Support 1-day diff words (just now, yesterday, tomorrow)
var_dump(Carbon::localeHasDiffOneDayWords('en'));                                // bool(true)
var_dump(Carbon::localeHasDiffOneDayWords('zh_TW'));                             // bool(false)
// Support 2-days diff words (before yesterday, after tomorrow)
var_dump(Carbon::localeHasDiffTwoDayWords('en'));                                // bool(true)
var_dump(Carbon::localeHasDiffTwoDayWords('zh_TW'));                             // bool(false)
// Support short units (1y = 1 year, 1mo = 1 month, etc.)
var_dump(Carbon::localeHasShortUnits('en'));                                     // bool(true)
var_dump(Carbon::localeHasShortUnits('zh_TW'));                                  // bool(false)
// Support period syntax (X times, every X, from X, to X)
var_dump(Carbon::localeHasPeriodSyntax('en'));                                   // bool(true)
var_dump(Carbon::localeHasPeriodSyntax('zh_TW'));                                // bool(false)

So, here is the new recommended way to handle internationalization with Carbon.

$date = Carbon::now()->locale('fr_FR');

echo $date->locale();            // fr_FR
echo "\n";
echo $date->diffForHumans();     // il y a 1 seconde
echo "\n";
echo $date->monthName;           // aoΓ»t
echo "\n";
echo $date->isoFormat('LLLL');   // vendredi 9 aoΓ»t 2019 15:17

The ->locale() method only change the language for the current instance and has precedence over global settings. We recommend you this approach so you can't have conflict with other places or third-party libraries that could use Carbon. Nevertheless, to avoid calling ->locale() each time, you can use factories.

// Let say Martin from Paris and John from Chicago play chess
$martinDateFactory = new Factory([
    'locale' => 'fr_FR',
    'timezone' => 'Europe/Paris',
]);
$johnDateFactory = new Factory([
    'locale' => 'en_US',
    'timezone' => 'America/Chicago',
]);
// Each one will see date in his own language and timezone

// When Martin moves, we display things in French, but we notify John in English:
$gameStart = Carbon::parse('2018-06-15 12:34:00', 'UTC');
$move = Carbon::now('UTC');
$toDisplay = $martinDateFactory->make($gameStart)->isoFormat('lll')."\n".
    $martinDateFactory->make($move)->calendar()."\n";
$notificationForJohn = $johnDateFactory->make($gameStart)->isoFormat('lll')."\n".
    $johnDateFactory->make($move)->calendar()."\n";
echo $toDisplay;
/*
15 juin 2018 12:34
Aujourd’hui Γ  15:17
*/

echo $notificationForJohn;
/*
Jun 15, 2018 12:34 PM
Today at 3:17 PM
*/

You can call any static Carbon method on a factory (make, now, yesterday, tomorrow, parse, create, etc.) Factory (and FactoryImmutable that generates CarbonImmutable instances) are the best way to keep things organized and isolated. As often as possible we recommend you to work with UTC dates, then apply locally (or with a factory) the timezone and the language before displaying dates to the user.

What factory actually do is using the method name as static constructor then call settings() method which is a way to group in one call settings of locale, timezone, months/year overflow, etc. (See references for complete list.)

$factory = new Factory([
    'locale' => 'fr_FR',
    'timezone' => 'Europe/Paris',
]);
$factory->now(); // You can recall $factory as needed to generate new instances with same settings
// is equivalent to:
Carbon::now()->settings([
    'locale' => 'fr_FR',
    'timezone' => 'Europe/Paris',
]);
// Important note: timezone setting calls ->shiftTimezone() and not ->setTimezone(),
// It means it does not just set the timezone, but shift the time too:
echo Carbon::today()->setTimezone('Asia/Tokyo')->format('d/m G\h e');        // 09/08 9h Asia/Tokyo
echo "\n";
echo Carbon::today()->shiftTimezone('Asia/Tokyo')->format('d/m G\h e');      // 09/08 0h Asia/Tokyo

Factory settings can be changed afterward with setSettings(array $settings) or to merge new settings with existing ones mergeSettings(array $settings) and the class to generate can be initialized as the second argument of the construct then changed later with setClassName(string $className).

$factory = new Factory(['locale' => 'ja'], CarbonImmutable::class);
var_dump($factory->now()->locale);                                           // string(2) "ja"
var_dump(get_class($factory->now()));                                        // string(22) "Carbon\CarbonImmutable"

class MyCustomCarbonSubClass extends Carbon { /* ... */ }
$factory
    ->setSettings(['locale' => 'zh_CN'])
    ->setClassName(MyCustomCarbonSubClass::class);
var_dump($factory->now()->locale);                                           // string(5) "zh_CN"
var_dump(get_class($factory->now()));                                        // string(22) "MyCustomCarbonSubClass"

Previously there was Carbon::setLocale that set globally the locale. But as for our other static setters, we highly discourage you to use it. It breaks the principle of isolation because the configuration will apply for every class that uses Carbon.

You also may know formatLocalized() method from Carbon 1. This method still works the same in Carbon 2 but you should better use isoFormat() instead.

->isoFormat(string $format): string use ISO format rather than PHP-specific format and use inner translations rather than language packages you need to install on every machine where you deploy your application. isoFormat method is compatible with momentjs format method, it means you can use same format strings as you may have used in moment from front-end or node.js. Here are some examples:

$date = Carbon::parse('2018-06-15 17:34:15.984512', 'UTC');
echo $date->isoFormat('MMMM Do YYYY, h:mm:ss a'); // June 15th 2018, 5:34:15 pm
echo "\n";
echo $date->isoFormat('dddd');           // Friday
echo "\n";
echo $date->isoFormat('MMM Do YY');      // Jun 15th 18
echo "\n";
echo $date->isoFormat('YYYY [escaped] YYYY'); // 2018 escaped 2018

You can also create date from ISO formatted strings:

$date = Carbon::createFromIsoFormat('!YYYY-MMMM-D h:mm:ss a', '2019-January-3 6:33:24 pm', 'UTC');
echo $date->isoFormat('M/D/YY HH:mm'); // 1/3/19 18:33

->isoFormat use contextualized methods for day names and month names as they can have multiple forms in some languages, see the following examples:

$date = Carbon::parse('2018-03-16')->locale('uk');
echo $date->getTranslatedDayName('[Π²] dddd'); // ΠΏβ€™ΡΡ‚Π½ΠΈΡ†ΡŽ
// By providing a context, we're saying translate day name like in a format such as [Π²] dddd
// So the context itself has to be translated first consistently.
echo "\n";
echo $date->getTranslatedDayName('[наступної] dddd'); // п’ятниці
echo "\n";
echo $date->getTranslatedDayName('dddd, MMM'); // п’ятниця
echo "\n";
// The same goes for short/minified variants:
echo $date->getTranslatedShortDayName('[наступної] dd'); // ΠΏΡ‚
echo "\n";
echo $date->getTranslatedMinDayName('[наступної] ddd'); // ΠΏΡ‚
echo "\n";

// And the same goes for months
$date->locale('ru');
echo $date->getTranslatedMonthName('Do MMMM'); // ΠΌΠ°Ρ€Ρ‚Π°
echo "\n";
echo $date->getTranslatedMonthName('MMMM YYYY'); // ΠΌΠ°Ρ€Ρ‚
echo "\n";
// Short variant
echo $date->getTranslatedShortMonthName('Do MMM'); // ΠΌΠ°Ρ€
echo "\n";
echo $date->getTranslatedShortMonthName('MMM YYYY'); // ΠΌΠ°Ρ€
echo "\n";

// And so you can force a different context to get those variants:
echo $date->isoFormat('Do MMMM');        // 16-Π³ΠΎ ΠΌΠ°Ρ€Ρ‚Π°
echo "\n";
echo $date->isoFormat('MMMM YYYY');      // ΠΌΠ°Ρ€Ρ‚ 2018
echo "\n";
echo $date->isoFormat('Do MMMM', 'MMMM YYYY'); // 16-Π³ΠΎ ΠΌΠ°Ρ€Ρ‚
echo "\n";
echo $date->isoFormat('MMMM YYYY', 'Do MMMM'); // ΠΌΠ°Ρ€Ρ‚Π° 2018
echo "\n";

Here is the complete list of available replacements (examples given with $date = Carbon::parse('2017-01-05 17:04:05.084512');):

Code Example Description
OD 5 Day number with alternative numbers such as δΈ‰ for 3 if locale is ja_JP
OM 1 Month number with alternative numbers such as ၀၂ for 2 if locale is my_MM
OY 2017 Year number with alternative numbers such as Ϋ±ΫΉΫΉΫΈ for 1998 if locale is fa
OH 17 24-hours number with alternative numbers such as α‚‘α‚“ for 13 if locale is shn_MM
Oh 5 12-hours number with alternative numbers such as 十一 for 11 if locale is lzh_TW
Om 4 Minute number with alternative numbers such as ΰ­«ΰ­­ for 57 if locale is or
Os 5 Second number with alternative numbers such as 十五 for 15 if locale is ja_JP
D 5 Day of month number (from 1 to 31)
DD 05 Day of month number with trailing zero (from 01 to 31)
Do 5th Day of month with ordinal suffix (from 1st to 31th), translatable
d 4 Day of week number (from 0 (Sunday) to 6 (Saturday))
dd Th Minified day name (from Su to Sa), transatable
ddd Thu Short day name (from Sun to Sat), transatable
dddd Thursday Day name (from Sunday to Saturday), transatable
DDD 5 Day of year number (from 1 to 366)
DDDD 005 Day of year number with trailing zeros (3 digits, from 001 to 366)
DDDo 5th Day of year number with ordinal suffix (from 1st to 366th), translatable
e 4 Day of week number (from 0 (Sunday) to 6 (Saturday)), similar to "d" but this one is translatable (takes first day of week of the current locale)
E 4 Day of week number (from 1 (Monday) to 7 (Sunday))
H 17 Hour from 0 to 23
HH 17 Hour with trailing zero from 00 to 23
h 5 Hour from 0 to 12
hh 05 Hour with trailing zero from 00 to 12
k 17 Hour from 1 to 24
kk 17 Hour with trailing zero from 01 to 24
m 4 Minute from 0 to 59
mm 04 Minute with trailing zero from 00 to 59
a pm Meridiem am/pm
A PM Meridiem AM/PM
s 5 Second from 0 to 59
ss 05 Second with trailing zero from 00 to 59
S 0 Second tenth
SS 08 Second hundredth (on 2 digits with trailing zero)
SSS 084 Millisecond (on 3 digits with trailing zeros)
SSSS 0845 Second ten thousandth (on 4 digits with trailing zeros)
SSSSS 08451 Second hundred thousandth (on 5 digits with trailing zeros)
SSSSSS 084512 Microsecond (on 6 digits with trailing zeros)
SSSSSSS 0845120 Second ten millionth (on 7 digits with trailing zeros)
SSSSSSSS 08451200 Second hundred millionth (on 8 digits with trailing zeros)
SSSSSSSSS 084512000 Nanosecond (on 9 digits with trailing zeros)
M 1 Month from 1 to 12
MM 01 Month with trailing zero from 01 to 12
MMM Jan Short month name, translatable
MMMM January Month name, translatable
Mo 1st Month with ordinal suffix from 1st to 12th, translatable
Q 1 Quarter from 1 to 4
Qo 1st Quarter with ordinal suffix from 1st to 4th, translatable
G 2017 ISO week year (see ISO week date)
GG 2017 ISO week year (on 2 digits with trailing zero)
GGG 2017 ISO week year (on 3 digits with trailing zeros)
GGGG 2017 ISO week year (on 4 digits with trailing zeros)
GGGGG 02017 ISO week year (on 5 digits with trailing zeros)
g 2017 Week year according to locale settings, translatable
gg 2017 Week year according to locale settings (on 2 digits with trailing zero), translatable
ggg 2017 Week year according to locale settings (on 3 digits with trailing zeros), translatable
gggg 2017 Week year according to locale settings (on 4 digits with trailing zeros), translatable
ggggg 02017 Week year according to locale settings (on 5 digits with trailing zeros), translatable
W 1 ISO week number in the year (see ISO week date)
WW 01 ISO week number in the year (on 2 digits with trailing zero)
Wo 1st ISO week number in the year with ordinal suffix, translatable
w 1 Week number in the year according to locale settings, translatable
ww 01 Week number in the year according to locale settings (on 2 digits with trailing zero)
wo 1st Week number in the year according to locale settings with ordinal suffix, translatable
x 1483635845085 Millisecond-precision timestamp (same as date.getTime() in JavaScript)
X 1483635845 Timestamp (number of seconds since 1970-01-01)
Y 2017 Full year from -9999 to 9999
YY 17 Year on 2 digits from 00 to 99
YYYY 2017 Year on 4 digits from 0000 to 9999
YYYYY 02017 Year on 5 digits from 00000 to 09999
YYYYYY +002017 Year on 5 digits with sign from -09999 to +09999
z utc Abbreviated time zone name
zz UTC Time zone name
Z +00:00 Time zone offset HH:mm
ZZ +0000 Time zone offset HHmm

Some macro-formats are also available. Here are examples of each in some languages:

Code en fr ja hr
LT
h:mm A
5:04 PM
HH:mm
17:04
HH:mm
17:04
H:mm
17:04
LTS
h:mm:ss A
5:04:05 PM
HH:mm:ss
17:04:05
HH:mm:ss
17:04:05
H:mm:ss
17:04:05
L

l
MM/DD/YYYY
01/05/2017
1/5/2017
DD/MM/YYYY
05/01/2017
5/1/2017
YYYY/MM/DD
2017/01/05
2017/1/5
DD.MM.YYYY
05.01.2017
5.1.2017
LL

ll
MMMM D, YYYY
January 5, 2017
Jan 5, 2017
D MMMM YYYY
5 janvier 2017
5 janv. 2017
YYYYεΉ΄M月Dζ—₯
2017εΉ΄1月5ζ—₯
2017εΉ΄1月5ζ—₯
D. MMMM YYYY
5. siječanj 2017
5. sij. 2017
LLL

lll
MMMM D, YYYY h:mm A
January 5, 2017 5:04 PM
Jan 5, 2017 5:04 PM
D MMMM YYYY HH:mm
5 janvier 2017 17:04
5 janv. 2017 17:04
YYYYεΉ΄M月Dζ—₯ HH:mm
2017εΉ΄1月5ζ—₯ 17:04
2017εΉ΄1月5ζ—₯ 17:04
D. MMMM YYYY H:mm
5. siječanj 2017 17:04
5. sij. 2017 17:04
LLLL

llll
dddd, MMMM D, YYYY h:mm A
Thursday, January 5, 2017 5:04 PM
Thu, Jan 5, 2017 5:04 PM
dddd D MMMM YYYY HH:mm
jeudi 5 janvier 2017 17:04
jeu. 5 janv. 2017 17:04
YYYYεΉ΄M月Dζ—₯ dddd HH:mm
2017εΉ΄1月5ζ—₯ ζœ¨ζ›œζ—₯ 17:04
2017εΉ΄1月5ζ—₯ 木 17:04
dddd, D. MMMM YYYY H:mm
četvrtak, 5. siječanj 2017 17:04
čet., 5. sij. 2017 17:04

When you use macro-formats with createFromIsoFormat you can specify a locale to select which language the macro-format should be searched in.

$date = Carbon::createFromIsoFormat('LLLL', 'Monday 11 March 2019 16:28', null, 'fr');
echo $date->isoFormat('M/D/YY HH:mm'); // 3/11/19 16:28

An other usefull translated method is calendar($referenceTime = null, array $formats = []): string:

$date = CarbonImmutable::now();
echo $date->calendar();                                      // Today at 3:17 PM
echo "\n";
echo $date->sub('1 day 3 hours')->calendar();                // Yesterday at 12:17 PM
echo "\n";
echo $date->sub('3 days 10 hours 23 minutes')->calendar();   // Last Tuesday at 4:54 AM
echo "\n";
echo $date->sub('8 days')->calendar();                       // 08/01/2019
echo "\n";
echo $date->add('1 day 3 hours')->calendar();                // Tomorrow at 6:17 PM
echo "\n";
echo $date->add('3 days 10 hours 23 minutes')->calendar();   // Tuesday at 1:40 AM
echo "\n";
echo $date->add('8 days')->calendar();                       // 08/17/2019
echo "\n";
echo $date->locale('fr')->calendar();                        // Aujourd’hui Γ  15:17

If you know momentjs, then it works the same way. You can pass a reference date as second argument, else now is used. And you can customize one or more formats using the second argument (formats to pass as array keys are: sameDay, nextDay, nextWeek, lastDay, lastWeek and sameElse):

$date1 = CarbonImmutable::parse('2018-01-01 12:00:00');
$date2 = CarbonImmutable::parse('2018-01-02 8:00:00');

echo $date1->calendar($date2, [
    'lastDay' => '[Previous day at] LT',
]);
// Previous day at 12:00 PM

Click here is an overview of the 281 locales (and 823 regional variants) supported by the last Carbon version:

Locale
Diff syntax
1-day diff
2-days diff
Month names
Week days
Units
Short units
Period
aa βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
af βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
agq βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
agr βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ak βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
am βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
an βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
anp βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ar βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
as βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
asa βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ast βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ayc βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
az βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
bas βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
be βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
bem βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ber βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
bez βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
bg βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
bhb βœ… βœ… βœ… ❌ ❌ ❌ ❌ βœ…
bho βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
bi βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
bm ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
bn βœ… βœ… ❌ βœ… βœ… βœ… βœ… βœ…
bo ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
br ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
brx βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
bs βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
byn βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ca βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ccp βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ce βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
cgg βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
chr βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
cmn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
crh βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
cs βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
csb ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
cu βœ… βœ… βœ… βœ… ❌ βœ… βœ… βœ…
cv ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
cy βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
da βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
dav βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
de βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
dje βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
doi βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
dsb βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
dua βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
dv βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
dyo βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
dz βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ebu βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ee βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
el βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
en βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
eo βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
es βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
et βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
eu βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
ewo βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
fa βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
ff βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
fi βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
fil βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
fo βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
fr βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
fur ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
fy ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
ga βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
gd ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
gez βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
gl βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
gom ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
gsw ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
gu βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
guz βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
gv βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ha βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
hak βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
haw βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
he βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
hi βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
hif βœ… βœ… βœ… ❌ βœ… βœ… βœ… βœ…
hne βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
hr βœ… ❌ βœ… βœ… βœ… βœ… βœ… ❌
hsb βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ht βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
hu βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
hy βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
i18n βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ia βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
id βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
ig βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ii βœ… βœ… βœ… ❌ βœ… βœ… βœ… βœ…
ik βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
in βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
is βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
it βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
iu βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
iw βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ja βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
jgo βœ… βœ… βœ… ❌ ❌ ❌ ❌ βœ…
jmc βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
jv ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
ka βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
kab βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
kam βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
kde βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
kea βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
khq βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ki βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
kk βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
kkj βœ… βœ… βœ… ❌ ❌ ❌ ❌ βœ…
kl βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
kln βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
km βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
kn ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
ko βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
kok βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ks βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ksb βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ksf βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ksh βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ku βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
kw βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ky ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
lag βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
lb ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
lg βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
li βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
lij βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
lkt βœ… βœ… βœ… ❌ ❌ βœ… βœ… βœ…
ln βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
lo ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
lrc βœ… βœ… βœ… ❌ ❌ ❌ ❌ βœ…
lt βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
lu βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
luo βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
luy βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
lv βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
lzh βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mag βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
mai βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mas βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
me ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
mer βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mfe βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mg βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mgh βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
mgo βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
mhr βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mi ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
miq βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
mjw βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
mk βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
ml ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
mn βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
mni βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
mo βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
mr βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
ms βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
mt ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
mua βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
my βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
mzn βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
nan βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
naq βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nb βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nd βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nds βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ne βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
nhn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
niu βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nl βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nmg βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
nn ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
nnh βœ… βœ… βœ… ❌ ❌ ❌ ❌ βœ…
no βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nr βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
nso βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nus βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
nyn βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
oc βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
om βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
or ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
os βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
pa ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
pap ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
pl βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
prg βœ… βœ… βœ… βœ… ❌ βœ… βœ… βœ…
ps βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
pt βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
qu βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
quz βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
raj βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
rm βœ… βœ… βœ… βœ… βœ… βœ… ❌ βœ…
rn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ro βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
rof βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ru βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
rw βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
rwk βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
sa βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sah βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
saq βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
sat βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sbp βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
sc βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
scr βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
sd ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
se ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
seh βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ses βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sg βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sgs βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sh βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
shi βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
shn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
shs βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
si ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
sid βœ… βœ… βœ… ❌ βœ… ❌ ❌ βœ…
sk βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
sl βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
sm βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
smn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
so βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sq βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
sr βœ… βœ… βœ… βœ… βœ… βœ… βœ… ❌
ss ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
st βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
sv βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
sw βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
szl βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
ta ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
tcy βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
te ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
teo ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
tet ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
tg ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
th βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
the βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ti βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tig βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tk βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tl ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
tlh ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
tn βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
to βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tpi βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tr βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
ts βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tt ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
twq βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
tzl ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
tzm ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
ug ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
uk βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
unm βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ur βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
uz βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
vai βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
ve βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
vi βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
vo βœ… βœ… βœ… βœ… ❌ βœ… βœ… βœ…
vun βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
wa βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
wae βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
wal βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
wo ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
xh βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
xog βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
yav βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
yi βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
yo ❌ ❌ ❌ βœ… βœ… βœ… βœ… ❌
yue βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
yuw βœ… βœ… βœ… βœ… βœ… ❌ ❌ βœ…
zgh βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…
zh βœ… ❌ ❌ βœ… βœ… βœ… βœ… ❌
zu βœ… βœ… βœ… βœ… βœ… βœ… βœ… βœ…

If you can add missing translations or missing languages, please go to translation tool, your help is welcome.

Note that if you use Laravel 5.5+, the locale will be automatically set according to current last App:setLocale execution. So diffForHumans, isoFormat, translatedFormat and localized properties such as ->dayName or ->monthName will be localized transparently.

Each Carbon, CarbonImmutable, CarbonInterval or CarbonPeriod instance is linked by default to a Carbon\Translator instance according to its locale set. You can get and/or change it using getLocalTranslator()/setLocalTranslator(Translator $translator).

If you prefer the date() pattern, you can use translatedFormat() which works like format() but translate the string using the current locale.

$date = Carbon::parse('2018-03-16 15:45')->locale('uk');

echo $date->translatedFormat('g:i a l jS F Y'); // 3:45 дня п’ятниця 16-Π³ΠΎ бСрСзня 2018

Be warned that some letters like W are not supported because they are not safely translatable and translatedFormat offers shorter syntax but less possibilities than isoFormat().

You can customize the behavior of the format() method to use any other method or a custom one instead of the native method from the PHP DateTime class:

$date = Carbon::parse('2018-03-16 15:45')->locale('ja');

echo $date->format('g:i a l jS F Y');    // 3:45 pm Friday 16th March 2018
echo "\n";

$date->settings(['formatFunction' => 'translatedFormat']);

echo $date->format('g:i a l jS F Y');    // 3:45 午後 ι‡‘ζ›œζ—₯ 16ζ—₯ 3月 2018
echo "\n";

$date->settings(['formatFunction' => 'isoFormat']);

echo $date->format('LL');                // 2018εΉ΄3月16ζ—₯
echo "\n";

// When you set a custom format() method you still can access the native method using rawFormat()
echo $date->rawFormat('D');              // Fri

You can translate a string from a language to an other using dates translations available in Carbon:

echo Carbon::translateTimeString('mercredi 8 juillet', 'fr', 'nl');
// woensdag 8 juli
echo "\n";

// You can select translations to use among available constants:
// - CarbonInterface::TRANSLATE_MONTHS
// - CarbonInterface::TRANSLATE_DAYS
// - CarbonInterface::TRANSLATE_UNITS
// - CarbonInterface::TRANSLATE_MERIDIEM
// - CarbonInterface::TRANSLATE_ALL (all above)
// You can combine them with pipes: like below (translate units and days but not months and meridiem):
echo Carbon::translateTimeString('mercredi 8 juillet + 3 jours', 'fr', 'nl', CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_UNITS);
// woensdag 8 juillet + 3 dagen

If input locale is not specified, Carbon::getLocale() is used instead. If output locale is not specified, "en" is used instead. You also can translate using the locale of the instance with:

echo Carbon::now()->locale('fr')->translateTimeStringTo('mercredi 8 juillet + 3 jours', 'nl');
// woensdag 8 juli + 3 dagen

You can use strings in any language directly to create a date object with parseFromLocale:

$date = Carbon::parseFromLocale('mercredi 6 mars 2019 + 3 jours', 'fr', 'UTC'); // timezone is optional

echo $date->isoFormat('LLLL'); // Saturday, March 9, 2019 12:00 AM

Or with custom format using createFromLocaleFormat (use the date() pattern for replacements):

$date = Carbon::createFromLocaleFormat('!d/F/y', 'fr', '25/AoΓ»t/19', 'Europe/Paris'); // timezone is optional

echo $date->isoFormat('LLLL'); // Sunday, August 25, 2019 12:00 AM

The equivalent method using ISO format is createFromLocaleIsoFormat:

$date = Carbon::createFromLocaleIsoFormat('!DD/MMMM/YY', 'fr', '25/AoΓ»t/19', 'Europe/Paris'); // timezone is optional

echo $date->isoFormat('LLLL'); // Sunday, August 25, 2019 12:00 AM

To get some interesting info about languages (such as complete ISO name or native name, region (for example to be displayed in a languages selector), you can use getAvailableLocalesInfo.

$zhTwInfo = Carbon::getAvailableLocalesInfo()['zh_TW'];
$srCyrlInfo = Carbon::getAvailableLocalesInfo()['sr_Cyrl'];
$caInfo = Carbon::getAvailableLocalesInfo()['ca'];

var_dump($zhTwInfo->getId());                      // string(5) "zh_TW"
var_dump($zhTwInfo->getNames());                  
/*
array(2) {
  ["isoName"]=>
  string(7) "Chinese"
  ["nativeName"]=>
  string(38) "δΈ­ζ–‡Β (ZhōngwΓ©n), 汉语,Β ζΌ’θͺž"
}
*/
var_dump($zhTwInfo->getCode());                    // string(2) "zh"
var_dump($zhTwInfo->getVariant());                 // NULL
var_dump($srCyrlInfo->getVariant());               // string(4) "Cyrl"
var_dump($zhTwInfo->getVariantName());             // NULL
var_dump($srCyrlInfo->getVariantName());           // string(8) "Cyrillic"
var_dump($zhTwInfo->getRegion());                  // string(2) "TW"
var_dump($srCyrlInfo->getRegion());                // NULL
var_dump($zhTwInfo->getRegionName());              // string(25) "Taiwan, Province of China"
var_dump($srCyrlInfo->getRegionName());            // NULL
var_dump($zhTwInfo->getFullIsoName());             // string(7) "Chinese"
var_dump($caInfo->getFullIsoName());               // string(18) "Catalan, Valencian"
var_dump($zhTwInfo->getFullNativeName());          // string(38) "δΈ­ζ–‡Β (ZhōngwΓ©n), 汉语,Β ζΌ’θͺž"
var_dump($caInfo->getFullNativeName());            // string(18) "catalΓ , valenciΓ "
var_dump($zhTwInfo->getIsoName());                 // string(7) "Chinese"
var_dump($caInfo->getIsoName());                   // string(7) "Catalan"
var_dump($zhTwInfo->getNativeName());              // string(20) "δΈ­ζ–‡Β (ZhōngwΓ©n)"
var_dump($caInfo->getNativeName());                // string(7) "catalΓ "
var_dump($zhTwInfo->getIsoDescription());          // string(35) "Chinese (Taiwan, Province of China)"
var_dump($srCyrlInfo->getIsoDescription());        // string(18) "Serbian (Cyrillic)"
var_dump($caInfo->getIsoDescription());            // string(7) "Catalan"
var_dump($zhTwInfo->getNativeDescription());       // string(48) "δΈ­ζ–‡Β (ZhōngwΓ©n) (Taiwan, Province of China)"
var_dump($srCyrlInfo->getNativeDescription());     // string(34) "српски јСзик (Cyrillic)"
var_dump($caInfo->getNativeDescription());         // string(7) "catalΓ "
var_dump($zhTwInfo->getFullIsoDescription());      // string(35) "Chinese (Taiwan, Province of China)"
var_dump($srCyrlInfo->getFullIsoDescription());    // string(18) "Serbian (Cyrillic)"
var_dump($caInfo->getFullIsoDescription());        // string(18) "Catalan, Valencian"
var_dump($zhTwInfo->getFullNativeDescription());   // string(66) "δΈ­ζ–‡Β (ZhōngwΓ©n), 汉语,Β ζΌ’θͺž (Taiwan, Province of China)"
var_dump($srCyrlInfo->getFullNativeDescription()); // string(34) "српски јСзик (Cyrillic)"
var_dump($caInfo->getFullNativeDescription());     // string(18) "catalΓ , valenciΓ "

$srCyrlInfo->setIsoName('foo, bar')->setNativeName('biz, baz');
var_dump($srCyrlInfo->getIsoName());               // string(3) "foo"
var_dump($srCyrlInfo->getFullIsoName());           // string(8) "foo, bar"
var_dump($srCyrlInfo->getFullIsoDescription());    // string(19) "foo, bar (Cyrillic)"
var_dump($srCyrlInfo->getNativeName());            // string(3) "biz"
var_dump($srCyrlInfo->getFullNativeName());        // string(8) "biz, baz"
var_dump($srCyrlInfo->getFullNativeDescription()); // string(19) "biz, baz (Cyrillic)"

// You can also access directly regions/languages lists:
var_dump(\Carbon\Language::all()['zh']);          
/*
array(2) {
  ["isoName"]=>
  string(7) "Chinese"
  ["nativeName"]=>
  string(38) "δΈ­ζ–‡Β (ZhōngwΓ©n), 汉语,Β ζΌ’θͺž"
}
*/
var_dump(\Carbon\Language::regions()['TW']);      
/*
string(25) "Taiwan, Province of China"
*/

Please let me thank some projects that helped us a lot to support more locales, and internationalization features:

  • jenssegers/date: many features were in this project that extends Carbon before being in Carbon itself.
  • momentjs: many features are inspired by momentjs and made to be compatible with this front-side pair project.
  • glibc was a strong base for adding and checking languages.
  • svenfuchs/rails-i18n also helped to add and check languages.
  • We used glosbe.com a lot to check translations and fill blanks.

Testing Aids

The testing methods allow you to set a Carbon instance (real or mock) to be returned when a "now" instance is created. The provided instance will be returned specifically under the following conditions:

  • A call to the static now() method, ex. Carbon::now()
  • When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
  • When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
  • The given instance will also be used as default relative moment for diff methods

$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
Carbon::setTestNow($knownDate);                        // set the mock (of course this could be a real mock object)
echo Carbon::getTestNow();                             // 2001-05-21 12:00:00
echo Carbon::now();                                    // 2001-05-21 12:00:00
echo new Carbon();                                     // 2001-05-21 12:00:00
echo Carbon::parse();                                  // 2001-05-21 12:00:00
echo new Carbon('now');                                // 2001-05-21 12:00:00
echo Carbon::parse('now');                             // 2001-05-21 12:00:00
echo Carbon::create(2001, 4, 21, 12)->diffForHumans(); // 1 month ago
var_dump(Carbon::hasTestNow());                        // bool(true)
Carbon::setTestNow();                                  // clear the mock
var_dump(Carbon::hasTestNow());                        // bool(false)
echo Carbon::now();                                    // 2019-08-09 15:17:17

A more meaning full example:

class SeasonalProduct
{
    protected $price;

    public function __construct($price)
    {
        $this->price = $price;
    }

    public function getPrice() {
        $multiplier = 1;
        if (Carbon::now()->month == 12) {
            $multiplier = 2;
        }

        return $this->price * $multiplier;
    }
}

$product = new SeasonalProduct(100);
Carbon::setTestNow(Carbon::parse('first day of March 2000'));
echo $product->getPrice();                                             // 100
Carbon::setTestNow(Carbon::parse('first day of December 2000'));
echo $product->getPrice();                                             // 200
Carbon::setTestNow(Carbon::parse('first day of May 2000'));
echo $product->getPrice();                                             // 100
Carbon::setTestNow();

Relative phrases are also mocked according to the given "now" instance.

$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
Carbon::setTestNow($knownDate);                        // set the mock
echo new Carbon('tomorrow');                           // 2001-05-22 00:00:00  ... notice the time !
echo new Carbon('yesterday');                          // 2001-05-20 00:00:00
echo new Carbon('next wednesday');                     // 2001-05-23 00:00:00
echo new Carbon('last friday');                        // 2001-05-18 00:00:00
echo new Carbon('this thursday');                      // 2001-05-24 00:00:00
Carbon::setTestNow();                                  // always clear it !

The list of words that are considered to be relative modifiers are:

  • +
  • -
  • ago
  • first
  • next
  • last
  • this
  • today
  • tomorrow
  • yesterday

Be aware that similar to the next(), previous() and modify() methods some of these relative modifiers will set the time to 00:00:00.

Carbon::parse($time, $tz) and new Carbon($time, $tz) both can take a timezone as second argument.

echo Carbon::parse('2012-9-5 23:26:11.223', 'Europe/Paris')->timezone->getName(); // Europe/Paris

Getters

The getters are implemented via PHP's __get() method. This enables you to access the value as if it was a property rather than a function call.

$dt = Carbon::parse('2012-10-5 23:26:11.123789');

// These getters specifically return integers, ie intval()
var_dump($dt->year);                                         // int(2012)
var_dump($dt->month);                                        // int(10)
var_dump($dt->day);                                          // int(5)
var_dump($dt->hour);                                         // int(23)
var_dump($dt->minute);                                       // int(26)
var_dump($dt->second);                                       // int(11)
var_dump($dt->micro);                                        // int(123789)
// dayOfWeek returns a number between 0 (sunday) and 6 (saturday)
var_dump($dt->dayOfWeek);                                    // int(5)
// dayOfWeekIso returns a number between 1 (monday) and 7 (sunday)
var_dump($dt->dayOfWeekIso);                                 // int(5)
var_dump($dt->englishDayOfWeek);                             // string(6) "Friday"
var_dump($dt->shortEnglishDayOfWeek);                        // string(3) "Fri"
var_dump($dt->locale('de')->dayName);                        // string(7) "Freitag"
var_dump($dt->locale('de')->shortDayName);                   // string(3) "Fr."
var_dump($dt->locale('de')->minDayName);                     // string(2) "Fr"
var_dump($dt->englishMonth);                                 // string(7) "October"
var_dump($dt->shortEnglishMonth);                            // string(3) "Oct"
var_dump($dt->locale('de')->monthName);                      // string(7) "Oktober"
var_dump($dt->locale('de')->shortMonthName);                 // string(3) "Okt"

// Following are deprecated, locale* and shortLocale* properties
// are translated using formatLocalized() based on LC_TIME language.
setlocale(LC_TIME, 'German');
var_dump($dt->localeDayOfWeek);                              // string(7) "Freitag"
var_dump($dt->shortLocaleDayOfWeek);                         // string(2) "Fr"
var_dump($dt->localeMonth);                                  // string(7) "Oktober"
var_dump($dt->shortLocaleMonth);                             // string(3) "Okt"
setlocale(LC_TIME, '');

var_dump($dt->dayOfYear);                                    // int(279)
var_dump($dt->weekNumberInMonth);                            // int(1)
// weekNumberInMonth consider weeks from monday to sunday, so the week 1 will
// contain 1 day if the month start with a sunday, and up to 7 if it starts with a monday
var_dump($dt->weekOfMonth);                                  // int(1)
// weekOfMonth will returns 1 for the 7 first days of the month, then 2 from the 8th to
// the 14th, 3 from the 15th to the 21st, 4 from 22nd to 28th and 5 above
var_dump($dt->weekOfYear);                                   // int(40)
var_dump($dt->daysInMonth);                                  // int(31)
var_dump($dt->timestamp);                                    // int(1349479571)
// Millisecond-precise timestamp (useful to pass it to JavaScript)
var_dump($dt->valueOf());                                    // float(1349479571124)
// Custom-precision timestamp
var_dump($dt->getPreciseTimestamp(6));                       // float(1.3494795711238E+15)
var_dump(Carbon::createFromDate(1975, 5, 21)->age);          // int(44) calculated vs now in the same tz
var_dump($dt->quarter);                                      // int(4)

// Returns an int of seconds difference from UTC (+/- sign included)
var_dump(Carbon::createFromTimestampUTC(0)->offset);         // int(0)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->offset);                // int(3600)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->getOffset());           // int(3600)

// Returns an int of hours difference from UTC (+/- sign included)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->offsetMinutes);         // int(60)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->offsetHours);           // int(1)

// Returns timezone offset as string
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->getOffsetString());     // string(6) "+01:00"

// Returns timezone as CarbonTimeZone
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->getTimezone());
/* object(Carbon\CarbonTimeZone)#3583 (2) {
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(12) "Europe/Paris"
} */

// Indicates if day light savings time is on
var_dump(Carbon::createFromDate(2012, 1, 1)->dst);           // bool(false)
var_dump(Carbon::createFromDate(2012, 9, 1)->dst);           // bool(false)
var_dump(Carbon::createFromDate(2012, 9, 1)->isDST());       // bool(false)

// Indicates if the instance is in the same timezone as the local timezone
var_dump(Carbon::now()->local);                              // bool(true)
var_dump(Carbon::now('America/Vancouver')->local);           // bool(false)
var_dump(Carbon::now()->isLocal());                          // bool(true)
var_dump(Carbon::now('America/Vancouver')->isLocal());       // bool(false)
var_dump(Carbon::now()->isUtc());                            // bool(true)
var_dump(Carbon::now('America/Vancouver')->isUtc());         // bool(false)
// can also be written ->isUTC()

// Indicates if the instance is in the UTC timezone
var_dump(Carbon::now()->utc);                                // bool(true)
// London is not UTC on summer time
var_dump(Carbon::parse('2018-10-01', 'Europe/London')->utc); // bool(false)
// London is UTC on winter time
var_dump(Carbon::parse('2018-11-01', 'Europe/London')->utc); // bool(true)
var_dump(Carbon::createFromTimestampUTC(0)->utc);            // bool(true)

// Gets the DateTimeZone instance
echo get_class(Carbon::now()->timezone);                     // Carbon\CarbonTimeZone
echo "\n";
echo get_class(Carbon::now()->tz);                           // Carbon\CarbonTimeZone
echo "\n";

// Gets the DateTimeZone instance name, shortcut for ->timezone->getName()
echo Carbon::now()->timezoneName;                            // UTC
echo "\n";
echo Carbon::now()->tzName;                                  // UTC
echo "\n";

// You can get any property dynamically too:
$unit = 'second';
var_dump(Carbon::now()->get($unit));                         // int(17)
// equivalent to:
var_dump(Carbon::now()->$unit);                              // int(17)
// If you have plural unit name, use singularUnit()
$unit = Carbon::singularUnit('seconds');
var_dump(Carbon::now()->get($unit));                         // int(17)
// Prefer using singularUnit() because some plurals are not the word with S:
var_dump(Carbon::pluralUnit('century'));                     // string(9) "centuries"
var_dump(Carbon::pluralUnit('millennium'));                  // string(9) "millennia"

Setters

The following setters are implemented via PHP's __set() method. Its good to take note here that none of the setters, with the obvious exception of explicitly setting the timezone, will change the timezone of the instance. Specifically, setting the timestamp will not set the corresponding timezone to UTC.

$dt = Carbon::now();

$dt->year = 1975;
$dt->month = 13;             // would force year++ and month = 1
$dt->month = 5;
$dt->day = 21;
$dt->hour = 22;
$dt->minute = 32;
$dt->second = 5;

$dt->timestamp = 169957925;  // This will not change the timezone
// Same as:
$dt->setTimestamp(169957925);
$dt->timestamp(169957925);

// Set the timezone via DateTimeZone instance or string
$dt->timezone = new DateTimeZone('Europe/London');
$dt->timezone = 'Europe/London';
$dt->tz = 'Europe/London';

// verbose way:
$dt->setYear(2001);
echo $dt->year;      // 2001
echo "\n";

// set/get method:
$dt->year(2002);
echo $dt->year();    // 0000-05-22 03:32:05
echo "\n";

// dynamic way:
$dt->set('year', 2003);
echo $dt->get('year'); // 2003
echo "\n";

// these methods exist for every units even for calculated properties such as:
echo $dt->dayOfYear(35)->format('Y-m-d'); // 2003-02-04

Weeks

If you are familiar with momentjs, you will find all week methods working the same. Most of them have an iso{Method} variant. Week methods follow the rules of the current locale (for example with en_US, the default locale, the first day of the week is Sunday, and the first week of the year is the one that contains January 1st). ISO methods follow the ISO 8601 norm, meaning weeks start with Monday and the first week of the year is the one containing January 4th.

$en = CarbonImmutable::now()->locale('en_US');
$ar = CarbonImmutable::now()->locale('ar');

var_dump($en->firstWeekDay);                           // int(0)
var_dump($en->lastWeekDay);                            // int(6)
var_dump($en->startOfWeek()->format('Y-m-d H:i'));     // string(16) "2019-08-04 00:00"
var_dump($en->endOfWeek()->format('Y-m-d H:i'));       // string(16) "2019-08-10 23:59"

echo "-----------\n";

// We still can force to use an other day as start/end of week
$start = $en->startOfWeek(Carbon::TUESDAY);
$end = $en->endOfWeek(Carbon::MONDAY);
var_dump($start->format('Y-m-d H:i'));                 // string(16) "2019-08-06 00:00"
var_dump($end->format('Y-m-d H:i'));                   // string(16) "2019-08-12 23:59"

echo "-----------\n";

var_dump($ar->firstWeekDay);                           // int(6)
var_dump($ar->lastWeekDay);                            // int(5)
var_dump($ar->startOfWeek()->format('Y-m-d H:i'));     // string(16) "2019-08-03 00:00"
var_dump($ar->endOfWeek()->format('Y-m-d H:i'));       // string(16) "2019-08-09 23:59"

$en = CarbonImmutable::parse('2015-02-05'); // use en_US as default locale

echo "-----------\n";

var_dump($en->weeksInYear());                          // int(52)
var_dump($en->isoWeeksInYear());                       // int(53)

$en = CarbonImmutable::parse('2017-02-05');

echo "-----------\n";

var_dump($en->week());                                 // int(6)
var_dump($en->isoWeek());                              // int(5)
var_dump($en->week(1)->format('Y-m-d H:i'));           // string(16) "2017-01-01 00:00"
var_dump($en->isoWeek(1)->format('Y-m-d H:i'));        // string(16) "2017-01-08 00:00"
var_dump($en->weekday());                              // int(0)
var_dump($en->isoWeekday());                           // int(7)
var_dump($en->weekday(3)->format('Y-m-d H:i'));        // string(16) "2017-02-08 00:00"
var_dump($en->isoWeekday(3)->format('Y-m-d H:i'));     // string(16) "2017-02-01 00:00"

$en = CarbonImmutable::parse('2017-01-01');

echo "-----------\n";

var_dump($en->weekYear());                             // int(2017)
var_dump($en->isoWeekYear());                          // int(2016)
var_dump($en->weekYear(2016)->format('Y-m-d H:i'));    // string(16) "2015-12-27 00:00"
var_dump($en->isoWeekYear(2016)->format('Y-m-d H:i')); // string(16) "2017-01-01 00:00"
var_dump($en->weekYear(2015)->format('Y-m-d H:i'));    // string(16) "2014-12-28 00:00"
var_dump($en->isoWeekYear(2015)->format('Y-m-d H:i')); // string(16) "2015-12-27 00:00"

// Note you still can force first day of week and year to use:
$en = CarbonImmutable::parse('2017-01-01');

echo "-----------\n";

var_dump($en->weeksInYear(null, 6, 12));               // int(52)
var_dump($en->isoWeeksInYear(null, 6, 12));            // int(52)
var_dump($en->week(null, 6, 12));                      // int(52)
var_dump($en->isoWeek(null, 6, 12));                   // int(52)
var_dump($en->weekYear(null, 6, 12));                  // int(2016)
var_dump($en->isoWeekYear(null, 6, 12));               // int(2016)
var_dump($en->weekYear(2016, 6, 12)->format('Y-m-d H:i')); // string(16) "2017-01-01 00:00"
var_dump($en->isoWeekYear(2016, 6, 12)->format('Y-m-d H:i')); // string(16) "2017-01-01 00:00"
// Then you can see using a method or its ISO variant return identical results

Fluent Setters

You can call any base unit as a setter or some grouped setters:

$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->setDate(1975, 5, 21)->setTimeFromTimeString('22:32:05')->toDateTimeString();
$dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();

// All allow microsecond as optional argument
$dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->microsecond(123456)->toDateTimeString();
$dt->setDate(1975, 5, 21)->setTime(22, 32, 5, 123456)->toDateTimeString();
$dt->setDate(1975, 5, 21)->setTimeFromTimeString('22:32:05.123456')->toDateTimeString();
$dt->setDateTime(1975, 5, 21, 22, 32, 5, 123456)->toDateTimeString();

$dt->timestamp(169957925); // Note: timestamps are UTC but do not change the date timezone

$dt->timezone('Europe/London')->tz('America/Toronto')->setTimezone('America/Vancouver');

You also can set date and time separately from other DateTime/Carbon objects:

$source1 = new Carbon('2010-05-16 22:40:10.1');

$dt = new Carbon('2001-01-01 01:01:01.2');
$dt->setTimeFrom($source1);

echo $dt; // 2001-01-01 22:40:10

$source2 = new DateTime('2013-09-01 09:22:56.2');

$dt->setDateFrom($source2);

echo $dt; // 2013-09-01 22:40:10

$dt->setDateTimeFrom($source2); // set date and time including microseconds
// bot not settings as locale, timezone, options.

IsSet

The PHP function __isset() is implemented. This was done as some external systems (ex. Twig) validate the existence of a property before using it. This is done using the isset() or empty() method. You can read more about these on the PHP site: __isset(), isset(), empty().

var_dump(isset(Carbon::now()->iDoNotExist));       // bool(false)
var_dump(isset(Carbon::now()->hour));              // bool(true)
var_dump(empty(Carbon::now()->iDoNotExist));       // bool(true)
var_dump(empty(Carbon::now()->year));              // bool(false)

String Formatting

All of the available toXXXString() methods rely on the base class method DateTime::format(). You'll notice the __toString() method is defined which allows a Carbon instance to be printed as a pretty date time string when used in a string context.

$dt = Carbon::create(1975, 12, 25, 14, 15, 16);

var_dump($dt->toDateTimeString() == $dt);          // bool(true) => uses __toString()
echo $dt->toDateString();                          // 1975-12-25
echo $dt->toFormattedDateString();                 // Dec 25, 1975
echo $dt->toTimeString();                          // 14:15:16
echo $dt->toDateTimeString();                      // 1975-12-25 14:15:16
echo $dt->toDayDateTimeString();                   // Thu, Dec 25, 1975 2:15 PM

// ... of course format() is still available
echo $dt->format('l jS \\of F Y h:i:s A');         // Thursday 25th of December 1975 02:15:16 PM

// The reverse hasFormat method allows you to test if a string looks like a given format
var_dump($dt->hasFormat('Thursday 25th December 1975 02:15:16 PM', 'l jS F Y h:i:s A')); // bool(true)

You can also set the default __toString() format (which defaults to Y-m-d H:i:s) thats used when type juggling occurs.

echo $dt;                                          // 1975-12-25 14:15:16
echo "\n";
$dt->settings([
    'toStringFormat' => 'jS \o\f F, Y g:i:s a',
]);
echo $dt;                                          // 25th of December, 1975 2:15:16 pm

// As any setting, you can get the current value for a given date using:
var_dump($dt->getSettings());
/*
array(3) {
  ["toStringFormat"]=>
  string(20) "jS \o\f F, Y g:i:s a"
  ["locale"]=>
  string(2) "en"
  ["timezone"]=>
  string(3) "UTC"
}*/

As part of the settings 'toStringFormat' can be used in factories too. It also may be a closure, so you can run any code on string cast.

If you use Carbon 1 or want to apply it globally as default format, you can use:

$dt = Carbon::create(1975, 12, 25, 14, 15, 16);
Carbon::setToStringFormat('jS \o\f F, Y g:i:s a');
echo $dt;                                          // 25th of December, 1975 2:15:16 pm
echo "\n";
Carbon::resetToStringFormat();
echo $dt;                                          // 1975-12-25 14:15:16

Note: For localization support see the Localization section.

Common Formats

The following are wrappers for the common formats provided in the DateTime class.

$dt = Carbon::createFromFormat('Y-m-d H:i:s.u', '2019-02-01 03:45:27.612584');

// $dt->toAtomString() is the same as $dt->format(DateTime::ATOM);
echo $dt->toAtomString();           // 2019-02-01T03:45:27+00:00
echo $dt->toCookieString();         // Friday, 01-Feb-2019 03:45:27 UTC

echo $dt->toIso8601String();        // 2019-02-01T03:45:27+00:00
// Be aware we chose to use the full-extended format of the ISO 8601 norm
// Natively, DateTime::ISO8601 format is not compatible with ISO-8601 as it
// is explained here in the PHP documentation:
// https://php.net/manual/class.datetime.php#datetime.constants.iso8601
// We consider it as a PHP mistake and chose not to provide method for this
// format, but you still can use it this way:
echo $dt->format(DateTime::ISO8601); // 2019-02-01T03:45:27+0000

echo $dt->toISOString();            // 2019-02-01T03:45:27.612584Z
echo $dt->toJSON();                 // 2019-02-01T03:45:27.612584Z

echo $dt->toIso8601ZuluString();    // 2019-02-01T03:45:27Z
echo $dt->toDateTimeLocalString();  // 2019-02-01T03:45:27
echo $dt->toRfc822String();         // Fri, 01 Feb 19 03:45:27 +0000
echo $dt->toRfc850String();         // Friday, 01-Feb-19 03:45:27 UTC
echo $dt->toRfc1036String();        // Fri, 01 Feb 19 03:45:27 +0000
echo $dt->toRfc1123String();        // Fri, 01 Feb 2019 03:45:27 +0000
echo $dt->toRfc2822String();        // Fri, 01 Feb 2019 03:45:27 +0000
echo $dt->toRfc3339String();        // 2019-02-01T03:45:27+00:00
echo $dt->toRfc7231String();        // Fri, 01 Feb 2019 03:45:27 GMT
echo $dt->toRssString();            // Fri, 01 Feb 2019 03:45:27 +0000
echo $dt->toW3cString();            // 2019-02-01T03:45:27+00:00

Conversion

$dt = Carbon::createFromFormat('Y-m-d H:i:s.u', '2019-02-01 03:45:27.612584');

var_dump($dt->toArray());
/*
array(12) {
  ["year"]=>
  int(2019)
  ["month"]=>
  int(2)
  ["day"]=>
  int(1)
  ["dayOfWeek"]=>
  int(5)
  ["dayOfYear"]=>
  int(32)
  ["hour"]=>
  int(3)
  ["minute"]=>
  int(45)
  ["second"]=>
  int(27)
  ["micro"]=>
  int(612584)
  ["timestamp"]=>
  int(1548992727)
  ["formatted"]=>
  string(19) "2019-02-01 03:45:27"
  ["timezone"]=>
  object(Carbon\CarbonTimeZone)#3588 (2) {
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(3) "UTC"
  }
}
*/

var_dump($dt->toObject());
/*
object(stdClass)#3588 (12) {
  ["year"]=>
  int(2019)
  ["month"]=>
  int(2)
  ["day"]=>
  int(1)
  ["dayOfWeek"]=>
  int(5)
  ["dayOfYear"]=>
  int(32)
  ["hour"]=>
  int(3)
  ["minute"]=>
  int(45)
  ["second"]=>
  int(27)
  ["micro"]=>
  int(612584)
  ["timestamp"]=>
  int(1548992727)
  ["formatted"]=>
  string(19) "2019-02-01 03:45:27"
  ["timezone"]=>
  object(Carbon\CarbonTimeZone)#3572 (2) {
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(3) "UTC"
  }
}
*/

var_dump($dt->toDate()); // Same as $dt->toDateTime()
/*
object(DateTime)#3588 (3) {
  ["date"]=>
  string(26) "2019-02-01 03:45:27.612584"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
*/

// Note than both Carbon and CarbonImmutable can be cast
// to both DateTime and DateTimeImmutable
var_dump($dt->toDateTimeImmutable());
/*
object(DateTimeImmutable)#3588 (3) {
  ["date"]=>
  string(26) "2019-02-01 03:45:27.612584"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
*/

class MySubClass extends Carbon {}
// MySubClass can be any class implementing CarbonInterface or a public static instance() method.

$copy = $dt->cast(MySubClass::class);
// Since 2.23.0, cast() can also take as argument any class that extend DateTime or DateTimeImmutable

echo get_class($copy).': '.$copy; // Same as MySubClass::instance($dt)
/*
MySubClass: 2019-02-01 03:45:27
*/

You can use the method carbonize to transform many things into a Carbon instance based on a given source instance used as reference on need. It returns a new instance.

$dt = Carbon::createFromFormat('Y-m-d H:i:s.u', '2019-02-01 03:45:27.612584', 'Europe/Paris');

// Can take a date string and will apply the timezone from reference object
var_dump($dt->carbonize('2019-03-21'));
/*
object(Carbon\Carbon)#3571 (3) {
  ["date"]=>
  string(26) "2019-03-21 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(12) "Europe/Paris"
}
*/

// If you pass a DatePeriod or CarbonPeriod, it will copy the period start
var_dump($dt->carbonize(CarbonPeriod::create('2019-12-10', '2020-01-05')));
/*
object(Carbon\Carbon)#3566 (3) {
  ["date"]=>
  string(26) "2019-12-10 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
*/

// If you pass a DateInterval or CarbonInterval, it will add the interval to
// the reference object
var_dump($dt->carbonize(CarbonInterval::days(3)));
/*
object(Carbon\Carbon)#3571 (3) {
  ["date"]=>
  string(26) "2019-02-04 03:45:27.612584"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(12) "Europe/Paris"
}
*/

Comparison

Simple comparison is offered up via the following functions. Remember that the comparison is done in the UTC timezone so things aren't always as they seem.

echo Carbon::now()->tzName;                        // UTC
$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');

echo $first->toDateTimeString();                   // 2012-09-05 23:26:11
echo $first->tzName;                               // UTC
echo $second->toDateTimeString();                  // 2012-09-05 20:26:11
echo $second->tzName;                              // America/Vancouver

var_dump($first->equalTo($second));                // bool(false)
// equalTo is also available on CarbonInterval and CarbonPeriod
var_dump($first->notEqualTo($second));             // bool(true)
// notEqualTo is also available on CarbonInterval and CarbonPeriod
var_dump($first->greaterThan($second));            // bool(false)
// greaterThan is also available on CarbonInterval
var_dump($first->greaterThanOrEqualTo($second));   // bool(false)
// greaterThanOrEqualTo is also available on CarbonInterval
var_dump($first->lessThan($second));               // bool(true)
// lessThan is also available on CarbonInterval
var_dump($first->lessThanOrEqualTo($second));      // bool(true)
// lessThanOrEqualTo is also available on CarbonInterval

$first->setDateTime(2012, 1, 1, 0, 0, 0);
$second->setDateTime(2012, 1, 1, 0, 0, 0);         // Remember tz is '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)

// All have short hand aliases and PHP equivalent code:

var_dump($first->eq($second));                     // bool(false)
var_dump($first->equalTo($second));                // bool(false)
var_dump($first == $second);                       // bool(false)

var_dump($first->ne($second));                     // bool(true)
var_dump($first->notEqualTo($second));             // bool(true)
var_dump($first != $second);                       // bool(true)

var_dump($first->gt($second));                     // bool(false)
var_dump($first->greaterThan($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->greaterThanOrEqualTo($second));   // bool(false)
var_dump($first >= $second);                       // bool(false)

var_dump($first->lt($second));                     // bool(true)
var_dump($first->lessThan($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->lessThanOrEqualTo($second));      // bool(true)
var_dump($first <= $second);                       // bool(true)

Those methods use natural comparisons offered by PHP $date1 == $date2 so all of them will ignore milli/micro-seconds before PHP 7.1, then take them into account starting with 7.1.

To determine if the current instance is between two other instances you can use the aptly named between() method (or isBetween() alias). The third parameter indicates if an equal to comparison should be done. The default is true which determines if its between or equal to the boundaries.

$first = Carbon::create(2012, 9, 5, 1);
$second = Carbon::create(2012, 9, 5, 5);
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second));          // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second));          // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false));   // bool(false)
var_dump(Carbon::create(2012, 9, 5, 5)->isBetween($first, $second, false)); // bool(false)
// Rather than passing false as a third argument, you can use betweenExcluded
var_dump(Carbon::create(2012, 9, 5, 5)->betweenExcluded($first, $second));  // bool(false)
// All those methods are also available on CarbonInterval

Woah! Did you forget min() and max() ? Nope. That is covered as well by the suitably named min() and max() methods or minimum() and maximum() aliases. As usual the default parameter is now if null is specified.

$dt1 = Carbon::createMidnightDate(2012, 1, 1);
$dt2 = Carbon::createMidnightDate(2014, 1, 30);
echo $dt1->min($dt2);                              // 2012-01-01 00:00:00
echo $dt1->minimum($dt2);                          // 2012-01-01 00:00:00
// Also works with string
echo $dt1->minimum('2014-01-30');                  // 2012-01-01 00:00:00

$dt1 = Carbon::createMidnightDate(2012, 1, 1);
$dt2 = Carbon::createMidnightDate(2014, 1, 30);
echo $dt1->max($dt2);                              // 2014-01-30 00:00:00
echo $dt1->maximum($dt2);                          // 2014-01-30 00:00:00

// now is the default param
$dt1 = Carbon::createMidnightDate(2000, 1, 1);
echo $dt1->max();                                  // 2019-08-09 15:17:17
echo $dt1->maximum();                              // 2019-08-09 15:17:17

// Remember min and max PHP native function work fine with dates too:
echo max(Carbon::create('2002-03-15'), Carbon::create('2003-01-07'), Carbon::create('2002-08-25')); // 2003-01-07 00:00:00
echo min(Carbon::create('2002-03-15'), Carbon::create('2003-01-07'), Carbon::create('2002-08-25')); // 2002-03-15 00:00:00
// This way you can pass as many dates as you want and get no ambiguities about parameters order

$dt1 = Carbon::createMidnightDate(2010, 4, 1);
$dt2 = Carbon::createMidnightDate(2010, 3, 28);
$dt3 = Carbon::createMidnightDate(2010, 4, 16);

// returns the closest of two date (no matter before or after)
echo $dt1->closest($dt2, $dt3);                    // 2010-03-28 00:00:00
echo $dt2->closest($dt1, $dt3);                    // 2010-04-01 00:00:00
echo $dt3->closest($dt2, $dt1);                    // 2010-04-01 00:00:00

// returns the farthest of two date (no matter before or after)
echo $dt1->farthest($dt2, $dt3);                   // 2010-04-16 00:00:00
echo $dt2->farthest($dt1, $dt3);                   // 2010-04-16 00:00:00
echo $dt3->farthest($dt2, $dt1);                   // 2010-03-28 00:00:00

To handle the most used cases there are some simple helper functions that hopefully are obvious from their names. For the methods that compare to now() (ex. isToday()) in some manner, the now() is created in the same timezone as the instance.

$dt = Carbon::now();
$dt2 = Carbon::createFromDate(1987, 4, 23);

$dt->isSameAs('w', $dt2); // w is the date of the week, so this will return true if $dt and $dt2
                          // the same day of week (both monday or both sunday, etc.)
                          // you can use any format and combine as much as you want.
$dt->isFuture();
$dt->isPast();

$dt->isSameYear($dt2);
$dt->isCurrentYear();
$dt->isNextYear();
$dt->isLastYear();
$dt->isLongYear(); // see https://en.wikipedia.org/wiki/ISO_8601#Week_dates
$dt->isLeapYear();

$dt->isSameQuarter($dt2); // same quarter of the same year of the given date
$dt->isSameQuarter($dt2, false); // same quarter (3 months) no matter the year of the given date
$dt->isCurrentQuarter();
$dt->isNextQuarter(); // date is in the next quarter
$dt->isLastQuarter(); // in previous quarter

$dt->isSameMonth($dt2); // same month of the same year of the given date
$dt->isSameMonth($dt2, false); // same month no matter the year of the given date
$dt->isCurrentMonth();
$dt->isNextMonth();
$dt->isLastMonth();

$dt->isWeekday();
$dt->isWeekend();
$dt->isMonday();
$dt->isTuesday();
$dt->isWednesday();
$dt->isThursday();
$dt->isFriday();
$dt->isSaturday();
$dt->isSunday();
$dt->isDayOfWeek(Carbon::SATURDAY); // is a saturday
$dt->isLastOfMonth(); // is the last day of the month

$dt->is('Sunday');
$dt->is('June');
$dt->is('2019');
$dt->is('12:23');
$dt->is('2 June 2019');
$dt->is('06-02');

$dt->isSameDay($dt2); // Same day of same month of same year
$dt->isCurrentDay();
$dt->isYesterday();
$dt->isToday();
$dt->isTomorrow();
$dt->isNextWeek();
$dt->isLastWeek();

$dt->isSameHour($dt2);
$dt->isCurrentHour();
$dt->isSameMinute($dt2);
$dt->isCurrentMinute();
$dt->isSameSecond($dt2);
$dt->isCurrentSecond();

$dt->isStartOfDay(); // check if hour is 00:00:00
$dt->isMidnight(); // check if hour is 00:00:00 (isStartOfDay alias)
$dt->isEndOfDay(); // check if hour is 23:59:59
$dt->isMidday(); // check if hour is 12:00:00 (or other midday hour set with Carbon::setMidDayAt())
$born = Carbon::createFromDate(1987, 4, 23);
$noCake = Carbon::createFromDate(2014, 9, 26);
$yesCake = Carbon::createFromDate(2014, 4, 23);
$overTheHill = Carbon::now()->subYears(50);
var_dump($born->isBirthday($noCake));              // bool(false)
var_dump($born->isBirthday($yesCake));             // bool(true)
var_dump($overTheHill->isBirthday());              // bool(true) -> default compare it to today!

// isCurrentX, isSameX, isNextX and isLastX are available for each unit

Addition and Subtraction

The default DateTime provides a couple of different methods for easily adding and subtracting time. There is modify(), add() and sub(). modify() takes a magical date/time format string, 'last day of next month', that it parses and applies the modification while add() and sub() expect a DateInterval instance that's not so obvious, (e.g. new \DateInterval('P6YT5M') would mean 6 years and 5 minutes). Hopefully using these fluent functions will be more clear and easier to read after not seeing your code for a few weeks. But of course I don't make you choose since the base class functions are still available.

$dt = Carbon::create(2012, 1, 31, 0);

echo $dt->toDateTimeString();            // 2012-01-31 00:00:00

echo $dt->addCenturies(5);               // 2512-01-31 00:00:00
echo $dt->addCentury();                  // 2612-01-31 00:00:00
echo $dt->subCentury();                  // 2512-01-31 00:00:00
echo $dt->subCenturies(5);               // 2012-01-31 00:00:00

echo $dt->addYears(5);                   // 2017-01-31 00:00:00
echo $dt->addYear();                     // 2018-01-31 00:00:00
echo $dt->subYear();                     // 2017-01-31 00:00:00
echo $dt->subYears(5);                   // 2012-01-31 00:00:00

echo $dt->addQuarters(2);                // 2012-07-31 00:00:00
echo $dt->addQuarter();                  // 2012-10-31 00:00:00
echo $dt->subQuarter();                  // 2012-07-31 00:00:00
echo $dt->subQuarters(2);                // 2012-01-31 00:00:00

echo $dt->addMonths(60);                 // 2017-01-31 00:00:00
echo $dt->addMonth();                    // 2017-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps
echo $dt->subMonth();                    // 2017-02-03 00:00:00
echo $dt->subMonths(60);                 // 2012-02-03 00:00:00

echo $dt->addDays(29);                   // 2012-03-03 00:00:00
echo $dt->addDay();                      // 2012-03-04 00:00:00
echo $dt->subDay();                      // 2012-03-03 00:00:00
echo $dt->subDays(29);                   // 2012-02-03 00:00:00

echo $dt->addWeekdays(4);                // 2012-02-09 00:00:00
echo $dt->addWeekday();                  // 2012-02-10 00:00:00
echo $dt->subWeekday();                  // 2012-02-09 00:00:00
echo $dt->subWeekdays(4);                // 2012-02-03 00:00:00

echo $dt->addWeeks(3);                   // 2012-02-24 00:00:00
echo $dt->addWeek();                     // 2012-03-02 00:00:00
echo $dt->subWeek();                     // 2012-02-24 00:00:00
echo $dt->subWeeks(3);                   // 2012-02-03 00:00:00

echo $dt->addHours(24);                  // 2012-02-04 00:00:00
echo $dt->addHour();                     // 2012-02-04 01:00:00
echo $dt->subHour();                     // 2012-02-04 00:00:00
echo $dt->subHours(24);                  // 2012-02-03 00:00:00

echo $dt->addMinutes(61);                // 2012-02-03 01:01:00
echo $dt->addMinute();                   // 2012-02-03 01:02:00
echo $dt->subMinute();                   // 2012-02-03 01:01:00
echo $dt->subMinutes(61);                // 2012-02-03 00:00:00

echo $dt->addSeconds(61);                // 2012-02-03 00:01:01
echo $dt->addSecond();                   // 2012-02-03 00:01:02
echo $dt->subSecond();                   // 2012-02-03 00:01:01
echo $dt->subSeconds(61);                // 2012-02-03 00:00:00

echo $dt->addMilliseconds(61);           // 2012-02-03 00:00:00
echo $dt->addMillisecond();              // 2012-02-03 00:00:00
echo $dt->subMillisecond();              // 2012-02-03 00:00:00
echo $dt->subMillisecond(61);            // 2012-02-03 00:00:00

echo $dt->addMicroseconds(61);           // 2012-02-03 00:00:00
echo $dt->addMicrosecond();              // 2012-02-03 00:00:00
echo $dt->subMicrosecond();              // 2012-02-03 00:00:00
echo $dt->subMicroseconds(61);           // 2012-02-03 00:00:00

// and so on for any unit: millenium, century, decade, year, quarter, month, week, day, weekday,
// hour, minute, second, microsecond.

// Generic methods add/sub (or subtract alias) can take many different arguments:
echo $dt->add(61, 'seconds');                      // 2012-02-03 00:01:01
echo $dt->sub('1 day');                            // 2012-02-02 00:01:01
echo $dt->add(CarbonInterval::months(2));          // 2012-04-02 00:01:01
echo $dt->subtract(new DateInterval('PT1H'));      // 2012-04-01 23:01:01

For fun you can also pass negative values to addXXX(), in fact that's how subXXX() is implemented.

P.S. Don't worry if you forget and use addDay(5) or subYear(3), I have your back ;)

By default, Carbon relies on the underlying parent class PHP DateTime behavior. As a result adding or subtracting months can overflow, example:

$dt = CarbonImmutable::create(2017, 1, 31, 0);

echo $dt->addMonth();                    // 2017-03-03 00:00:00
echo "\n";
echo $dt->subMonths(2);                  // 2016-12-01 00:00:00

Since Carbon 2, you can set a local overflow behavior for each instance:

$dt = CarbonImmutable::create(2017, 1, 31, 0);
$dt->settings([
    'monthOverflow' => false,
]);

echo $dt->addMonth();                    // 2017-02-28 00:00:00
echo "\n";
echo $dt->subMonths(2);                  // 2016-11-30 00:00:00

Static helpers exist but are deprecated. If you're sure to need to apply global setting or work with version 1 of Carbon, you check the overflow static helpers section

You can prevent the overflow with Carbon::useMonthsOverflow(false)

Carbon::useMonthsOverflow(false);

$dt = Carbon::createMidnightDate(2017, 1, 31);

echo $dt->copy()->addMonth();            // 2017-02-28 00:00:00
echo "\n";
echo $dt->copy()->subMonths(2);          // 2016-11-30 00:00:00

// Call the method with true to allow overflow again
Carbon::resetMonthsOverflow(); // same as Carbon::useMonthsOverflow(true);

The method Carbon::shouldOverflowMonths() allows you to know if the overflow is currently enabled.

Carbon::useMonthsOverflow(false);

$dt = Carbon::createMidnightDate(2017, 1, 31);

echo $dt->copy()->addMonthWithOverflow();          // 2017-03-03 00:00:00
// plural addMonthsWithOverflow() method is also available
echo $dt->copy()->subMonthsWithOverflow(2);        // 2016-12-01 00:00:00
// singular subMonthWithOverflow() method is also available
echo $dt->copy()->addMonthNoOverflow();            // 2017-02-28 00:00:00
// plural addMonthsNoOverflow() method is also available
echo $dt->copy()->subMonthsNoOverflow(2);          // 2016-11-30 00:00:00
// singular subMonthNoOverflow() method is also available

echo $dt->copy()->addMonth();                      // 2017-02-28 00:00:00
echo $dt->copy()->subMonths(2);                    // 2016-11-30 00:00:00

Carbon::useMonthsOverflow(true);

$dt = Carbon::createMidnightDate(2017, 1, 31);

echo $dt->copy()->addMonthWithOverflow();          // 2017-03-03 00:00:00
echo $dt->copy()->subMonthsWithOverflow(2);        // 2016-12-01 00:00:00
echo $dt->copy()->addMonthNoOverflow();            // 2017-02-28 00:00:00
echo $dt->copy()->subMonthsNoOverflow(2);          // 2016-11-30 00:00:00

echo $dt->copy()->addMonth();                      // 2017-03-03 00:00:00
echo $dt->copy()->subMonths(2);                    // 2016-12-01 00:00:00

Carbon::resetMonthsOverflow();

From version 1.23.0, overflow control is also available on years:

Carbon::useYearsOverflow(false);

$dt = Carbon::createMidnightDate(2020, 2, 29);

var_dump(Carbon::shouldOverflowYears());           // bool(false)

echo $dt->copy()->addYearWithOverflow();           // 2021-03-01 00:00:00
// plural addYearsWithOverflow() method is also available
echo $dt->copy()->subYearsWithOverflow(2);         // 2018-03-01 00:00:00
// singular subYearWithOverflow() method is also available
echo $dt->copy()->addYearNoOverflow();             // 2021-02-28 00:00:00
// plural addYearsNoOverflow() method is also available
echo $dt->copy()->subYearsNoOverflow(2);           // 2018-02-28 00:00:00
// singular subYearNoOverflow() method is also available

echo $dt->copy()->addYear();                       // 2021-02-28 00:00:00
echo $dt->copy()->subYears(2);                     // 2018-02-28 00:00:00

Carbon::useYearsOverflow(true);

$dt = Carbon::createMidnightDate(2020, 2, 29);

var_dump(Carbon::shouldOverflowYears());           // bool(true)

echo $dt->copy()->addYearWithOverflow();           // 2021-03-01 00:00:00
echo $dt->copy()->subYearsWithOverflow(2);         // 2018-03-01 00:00:00
echo $dt->copy()->addYearNoOverflow();             // 2021-02-28 00:00:00
echo $dt->copy()->subYearsNoOverflow(2);           // 2018-02-28 00:00:00

echo $dt->copy()->addYear();                       // 2021-03-01 00:00:00
echo $dt->copy()->subYears(2);                     // 2018-03-01 00:00:00

Carbon::resetYearsOverflow();

You also can use ->addMonthsNoOverflow, ->subMonthsNoOverflow, ->addMonthsWithOverflow and ->subMonthsWithOverflow (or the singular methods with no s to "month") to explicitly add/sub months with or without overflow no matter the current mode and the same for any bigger unit (quarter, year, decade, century, millennium).

$dt = Carbon::createMidnightDate(2017, 1, 31)->settings([
    'monthOverflow' => false,
]);

echo $dt->copy()->addMonthWithOverflow();          // 2017-03-03 00:00:00
// plural addMonthsWithOverflow() method is also available
echo $dt->copy()->subMonthsWithOverflow(2);        // 2016-12-01 00:00:00
// singular subMonthWithOverflow() method is also available
echo $dt->copy()->addMonthNoOverflow();            // 2017-02-28 00:00:00
// plural addMonthsNoOverflow() method is also available
echo $dt->copy()->subMonthsNoOverflow(2);          // 2016-11-30 00:00:00
// singular subMonthNoOverflow() method is also available

echo $dt->copy()->addMonth();                      // 2017-02-28 00:00:00
echo $dt->copy()->subMonths(2);                    // 2016-11-30 00:00:00

$dt = Carbon::createMidnightDate(2017, 1, 31)->settings([
    'monthOverflow' => true,
]);

echo $dt->copy()->addMonthWithOverflow();          // 2017-03-03 00:00:00
echo $dt->copy()->subMonthsWithOverflow(2);        // 2016-12-01 00:00:00
echo $dt->copy()->addMonthNoOverflow();            // 2017-02-28 00:00:00
echo $dt->copy()->subMonthsNoOverflow(2);          // 2016-11-30 00:00:00

echo $dt->copy()->addMonth();                      // 2017-03-03 00:00:00
echo $dt->copy()->subMonths(2);                    // 2016-12-01 00:00:00

The same is available for years.

You also can control overflow for any unit when working with unknown inputs:

$dt = CarbonImmutable::create(2018, 8, 30, 12, 00, 00);

// Add hours without overflowing day
echo $dt->addUnitNoOverflow('hour', 7, 'day');     // 2018-08-30 19:00:00
echo "\n";
echo $dt->addUnitNoOverflow('hour', 14, 'day');    // 2018-08-30 23:59:59
echo "\n";
echo $dt->addUnitNoOverflow('hour', 48, 'day');    // 2018-08-30 23:59:59

echo "\n-------\n";

// Substract hours without overflowing day
echo $dt->subUnitNoOverflow('hour', 7, 'day');     // 2018-08-30 05:00:00
echo "\n";
echo $dt->subUnitNoOverflow('hour', 14, 'day');    // 2018-08-30 00:00:00
echo "\n";
echo $dt->subUnitNoOverflow('hour', 48, 'day');    // 2018-08-30 00:00:00

echo "\n-------\n";

// Set hours without overflowing day
echo $dt->setUnitNoOverflow('hour', -7, 'day');    // 2018-08-30 00:00:00
echo "\n";
echo $dt->setUnitNoOverflow('hour', 14, 'day');    // 2018-08-30 14:00:00
echo "\n";
echo $dt->setUnitNoOverflow('hour', 25, 'day');    // 2018-08-30 23:59:59

echo "\n-------\n";

// Adding hours without overflowing month
echo $dt->addUnitNoOverflow('hour', 7, 'month');   // 2018-08-30 19:00:00
echo "\n";
echo $dt->addUnitNoOverflow('hour', 14, 'month');  // 2018-08-31 02:00:00
echo "\n";
echo $dt->addUnitNoOverflow('hour', 48, 'month');  // 2018-08-31 23:59:59

Any modifiable unit can be passed as argument of those methods:

$units = [];
foreach (['millennium', 'century', 'decade', 'year', 'quarter', 'month', 'week', 'weekday', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'] as $unit) {
    $units[$unit] = Carbon::isModifiableUnit($unit);
}

echo json_encode($units, JSON_PRETTY_PRINT);
/* {
    "millennium": true,
    "century": true,
    "decade": true,
    "year": true,
    "quarter": true,
    "month": true,
    "week": true,
    "weekday": true,
    "day": true,
    "hour": true,
    "minute": true,
    "second": true,
    "millisecond": true,
    "microsecond": true
} */

Difference

As Carbon extends DateTime it inherit its methods such as diff() that take a second date object as argument and returns a DateInterval instance.

We also provide diffAsCarbonInterval() act like diff() but returns a CarbonInterval instance. Check CarbonInterval chapter for more information. Carbon add diff methods for each unit too such as diffInYears(), diffInMonths() and so on. diffAsCarbonInterval() and diffIn*() and floatDiffIn*() methods all can take 2 optional arguments: date to compare with (if missing, now is used instead), and an absolute boolean option (true by default) that make the method return an absolute value no matter which date is greater than the other. If set to false, it returns negative value when the instance the method is called on is greater than the compared date (first argument or now). Note that diff() prototype is different: its first argument (the date) is mandatory and its second argument (the absolute option) defaults to false.

These functions always return the total difference expressed in the specified time requested. This differs from the base class diff() function where an interval of 122 seconds would be returned as 2 minutes and 2 seconds via a DateInterval instance. The diffInMinutes() function would simply return 2 while diffInSeconds() would return 122. All values are truncated and not rounded. Each function below has a default first parameter which is the Carbon instance to compare to, or null if you want to use now(). The 2nd parameter again is optional and indicates if you want the return value to be the absolute value or a relative value that might have a - (negative) sign if the passed in date is less than the current instance. This will default to true, return the absolute value.

echo Carbon::now('America/Vancouver')->diffInSeconds(Carbon::now('Europe/London')); // 0

$dtOttawa = Carbon::createMidnightDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createMidnightDate(2000, 1, 1, 'America/Vancouver');
echo $dtOttawa->diffInHours($dtVancouver);                             // 3
echo $dtVancouver->diffInHours($dtOttawa);                             // 3

echo $dtOttawa->diffInHours($dtVancouver, false);                      // 3
echo $dtVancouver->diffInHours($dtOttawa, false);                      // -3

$dt = Carbon::createMidnightDate(2012, 1, 31);
echo $dt->diffInDays($dt->copy()->addMonth());                         // 31
echo $dt->diffInDays($dt->copy()->subMonth(), false);                  // -31

$dt = Carbon::createMidnightDate(2012, 4, 30);
echo $dt->diffInDays($dt->copy()->addMonth());                         // 30
echo $dt->diffInDays($dt->copy()->addWeek());                          // 7

$dt = Carbon::createMidnightDate(2012, 1, 1);
echo $dt->diffInMinutes($dt->copy()->addSeconds(59));                  // 0
echo $dt->diffInMinutes($dt->copy()->addSeconds(60));                  // 1
echo $dt->diffInMinutes($dt->copy()->addSeconds(119));                 // 1
echo $dt->diffInMinutes($dt->copy()->addSeconds(120));                 // 2

echo $dt->addSeconds(120)->secondsSinceMidnight();                     // 120

$interval = $dt->diffAsCarbonInterval($dt->copy()->subYears(3), false);
// diffAsCarbonInterval use same arguments as diff($other, $absolute)
// (native method from \DateTime)
// except $absolute is true by default for diffAsCarbonInterval and false for diff
// $absolute parameter allow to get signed value if false, or always positive if true
echo ($interval->invert ? 'minus ' : 'plus ') . $interval->years;      // minus 3

These methods have int-truncated results. That means diffInMinutes returns 1 for any difference between 1 included and 2 excluded. But same methods are available for float results:

echo Carbon::parse('06:01:23.252987')->floatDiffInSeconds('06:02:34.321450');    // 71.068463
echo Carbon::parse('06:01:23')->floatDiffInMinutes('06:02:34');                  // 1.1833333333333
echo Carbon::parse('06:01:23')->floatDiffInHours('06:02:34');                    // 0.019722222222222
// Those methods are absolute by default but can return negative value
// setting the second argument to false when start date is greater than end date
echo Carbon::parse('12:01:23')->floatDiffInHours('06:02:34', false);             // -5.9802777777778
echo Carbon::parse('2000-01-01 12:00')->floatDiffInDays('2000-02-11 06:00');     // 40.75
echo Carbon::parse('2000-01-15 12:00')->floatDiffInMonths('2000-02-24 06:00');   // 1.301724137931
// floatDiffInMonths count as many full months as possible from the start date, then consider the number
// of days in the months for ending chunks to reach the end date
// So the following result (ending with 24 march is different from previous one with 24 february):
echo Carbon::parse('2000-02-15 12:00')->floatDiffInMonths('2000-03-24 06:00');   // 1.2822580645161
// floatDiffInYears apply the same logic (and so different results with leap years)
echo Carbon::parse('2000-02-15 12:00')->floatDiffInYears('2010-03-24 06:00');    // 10.100684931507

Important note about the daylight saving times (DST), by default PHP DateTime does not take DST into account, that means for example that a day with only 23 hours like March the 30th 2014 in London will be counted as 24 hours long.

$date = new DateTime('2014-03-30 00:00:00', new DateTimeZone('Europe/London')); // DST off
echo $date->modify('+25 hours')->format('H:i');                   // 01:00 (DST on, 24 hours only have been actually added)

Carbon follow this behavior too for add/sub/diff seconds/minutes/hours. But we provide methods to works with real hours using timestamp:

$date = new Carbon('2014-03-30 00:00:00', 'Europe/London');       // DST off
echo $date->addRealHours(25)->format('H:i');                      // 02:00 (DST on)
echo $date->diffInRealHours('2014-03-30 00:00:00');               // 25
echo $date->diffInHours('2014-03-30 00:00:00');                   // 26
echo $date->diffInRealMinutes('2014-03-30 00:00:00');             // 1500
echo $date->diffInMinutes('2014-03-30 00:00:00');                 // 1560
echo $date->diffInRealSeconds('2014-03-30 00:00:00');             // 90000
echo $date->diffInSeconds('2014-03-30 00:00:00');                 // 93600
echo $date->diffInRealMilliseconds('2014-03-30 00:00:00');        // 90000000
echo $date->diffInMilliseconds('2014-03-30 00:00:00');            // 93600000
echo $date->diffInRealMicroseconds('2014-03-30 00:00:00');        // 90000000000
echo $date->diffInMicroseconds('2014-03-30 00:00:00');            // 93600000000
echo $date->subRealHours(25)->format('H:i');                      // 00:00 (DST off)

// with float diff:
$date = new Carbon('2019-10-27 00:00:00', 'Europe/Paris');       
echo $date->floatDiffInRealHours('2019-10-28 12:30:00');          // 37.5
echo $date->floatDiffInHours('2019-10-28 12:30:00');              // 36.5
echo $date->floatDiffInRealMinutes('2019-10-28 12:00:30');        // 2220.5
echo $date->floatDiffInMinutes('2019-10-28 12:00:30');            // 2160.5
echo $date->floatDiffInRealSeconds('2019-10-28 12:00:00.5');      // 133200.5
echo $date->floatDiffInSeconds('2019-10-28 12:00:00.5');          // 129600.5
// above day unit, "real" will affect the decimal part based on hours and smaller units
echo $date->floatDiffInRealDays('2019-10-28 12:30:00');           // 1.5625
echo $date->floatDiffInDays('2019-10-28 12:30:00');               // 1.5208333333333
echo $date->floatDiffInRealMonths('2019-10-28 12:30:00');         // 0.050403225806452
echo $date->floatDiffInMonths('2019-10-28 12:30:00');             // 0.049059139784946
echo $date->floatDiffInRealYears('2019-10-28 12:30:00');          // 0.0042808219178082
echo $date->floatDiffInYears('2019-10-28 12:30:00');              // 0.0041666666666667

The same way you can use addRealX() and subRealX() on any unit.

There are also special filter functions diffInDaysFiltered(), diffInHoursFiltered() and diffFiltered(), to help you filter the difference by days, hours or a custom interval. For example to count the weekend days between two instances:

$dt = Carbon::create(2014, 1, 1);
$dt2 = Carbon::create(2014, 12, 31);
$daysForExtraCoding = $dt->diffInDaysFiltered(function(Carbon $date) {
   return $date->isWeekend();
}, $dt2);

echo $daysForExtraCoding;      // 104

$dt = Carbon::create(2014, 1, 1)->endOfDay();
$dt2 = $dt->copy()->startOfDay();
$littleHandRotations = $dt->diffFiltered(CarbonInterval::minute(), function(Carbon $date) {
   return $date->minute === 0;
}, $dt2, true); // true as last parameter returns absolute value

echo $littleHandRotations;     // 24

$date = Carbon::now()->addSeconds(3666);

echo $date->diffInSeconds();                       // 3665
echo $date->diffInMinutes();                       // 61
echo $date->diffInHours();                         // 1
echo $date->diffInDays();                          // 0

$date = Carbon::create(2016, 1, 5, 22, 40, 32);

echo $date->secondsSinceMidnight();                // 81632
echo $date->secondsUntilEndOfDay();                // 4767

$date1 = Carbon::createMidnightDate(2016, 1, 5);
$date2 = Carbon::createMidnightDate(2017, 3, 15);

echo $date1->diffInDays($date2);                   // 435
echo $date1->diffInWeekdays($date2);               // 311
echo $date1->diffInWeekendDays($date2);            // 124
echo $date1->diffInWeeks($date2);                  // 62
echo $date1->diffInMonths($date2);                 // 14
echo $date1->diffInYears($date2);                  // 1

All diffIn*Filtered method take 1 callable filter as required parameter and a date object as optional second parameter, if missing, now is used. You may also pass true as third parameter to get absolute values.

For advanced handle of the week/weekend days, use the following tools:

echo implode(', ', Carbon::getDays());                       // Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

$saturday = new Carbon('first saturday of 2019');
$sunday = new Carbon('first sunday of 2019');
$monday = new Carbon('first monday of 2019');

echo implode(', ', Carbon::getWeekendDays());                // 6, 0
var_dump($saturday->isWeekend());                            // bool(true)
var_dump($sunday->isWeekend());                              // bool(true)
var_dump($monday->isWeekend());                              // bool(false)

Carbon::setWeekendDays([
    Carbon::SUNDAY,
    Carbon::MONDAY,
]);

echo implode(', ', Carbon::getWeekendDays());                // 0, 1
var_dump($saturday->isWeekend());                            // bool(false)
var_dump($sunday->isWeekend());                              // bool(true)
var_dump($monday->isWeekend());                              // bool(true)

Carbon::setWeekendDays([
    Carbon::SATURDAY,
    Carbon::SUNDAY,
]);
// weekend days and start/end of week or not linked
Carbon::setWeekStartsAt(Carbon::FRIDAY);
Carbon::setWeekEndsAt(Carbon::WEDNESDAY); // and it does not need neither to precede the start

var_dump(Carbon::getWeekStartsAt() === Carbon::FRIDAY);      // bool(true)
var_dump(Carbon::getWeekEndsAt() === Carbon::WEDNESDAY);     // bool(true)
echo $saturday->copy()->startOfWeek()->toRfc850String();     // Friday, 02-Aug-19 00:00:00 UTC
echo $saturday->copy()->endOfWeek()->toRfc850String();       // Wednesday, 07-Aug-19 23:59:59 UTC

// Be very careful with those global setters, remember, some other
// code or third-party library in your app may expect initial weekend
// days to work properly.
Carbon::setWeekStartsAt(Carbon::MONDAY);
Carbon::setWeekEndsAt(Carbon::SUNDAY);

echo $saturday->copy()->startOfWeek()->toRfc850String();     // Monday, 29-Jul-19 00:00:00 UTC
echo $saturday->copy()->endOfWeek()->toRfc850String();       // Sunday, 04-Aug-19 23:59:59 UTC

Difference for Humans

It is easier for humans to read 1 month ago compared to 30 days ago. This is a common function seen in most date libraries so I thought I would add it here as well. The lone argument for the function is the other Carbon instance to diff against, and of course it defaults to now() if not specified.

This method will add a phrase after the difference value relative to the instance and the passed in instance. There are 4 possibilities:

  • When comparing a value in the past to default now:
    • 1 hour ago
    • 5 months ago
  • When comparing a value in the future to default now:
    • 1 hour from now
    • 5 months from now
  • When comparing a value in the past to another value:
    • 1 hour before
    • 5 months before
  • When comparing a value in the future to another value:
    • 1 hour after
    • 5 months after

You may also pass CarbonInterface::DIFF_ABSOLUTE as a 2nd parameter to remove the modifiers ago, from now, etc : diffForHumans($other, CarbonInterface::DIFF_ABSOLUTE), CarbonInterface::DIFF_RELATIVE_TO_NOW to get modifiers agoor from now, CarbonInterface::DIFF_RELATIVE_TO_OTHER to get the modifiers beforeor after or CarbonInterface::DIFF_RELATIVE_AUTO (default mode) to get the modifiers either ago/from now if the 2 second argument is null or before/after if not.

You may pass true as a 3rd parameter to use short syntax if available in the locale used : diffForHumans($other, CarbonInterface::DIFF_RELATIVE_AUTO, true).

You may pass a number between 1 and 6 as a 4th parameter to get the difference in multiple parts (more precise diff) : diffForHumans($other, CarbonInterface::DIFF_RELATIVE_AUTO, false, 4).

The $other instance can be a DateTime, a Carbon instance or any object that implement DateTimeInterface, if a string is passed it will be parsed to get a Carbon instance and if null is passed, Carbon::now() will be used instead.

To avoid having too much argument and mix the order, you can use the verbose methods:

  • shortAbsoluteDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • longAbsoluteDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • shortRelativeDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • longRelativeDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • shortRelativeToNowDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • longRelativeToNowDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • shortRelativeToOtherDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)
  • longRelativeToOtherDiffForHumans(DateTimeInterface | null $other = null, int $parts = 1)

PS: $other and $parts arguments can be swapped as need.

// The most typical usage is for comments
// The instance is the date the comment was created and its being compared to default now()
echo Carbon::now()->subDays(5)->diffForHumans();               // 5 days ago

echo Carbon::now()->diffForHumans(Carbon::now()->subYear());   // 11 months after

$dt = Carbon::createFromDate(2011, 8, 1);

echo $dt->diffForHumans($dt->copy()->addMonth());                        // 1 month before
echo $dt->diffForHumans($dt->copy()->subMonth());                        // 1 month after

echo Carbon::now()->addSeconds(5)->diffForHumans();                      // 4 seconds from now

echo Carbon::now()->subDays(24)->diffForHumans();                        // 3 weeks ago
echo Carbon::now()->subDays(24)->longAbsoluteDiffForHumans();            // 3 weeks

echo Carbon::parse('2019-08-03')->diffForHumans('2019-08-13');           // 1 week before
echo Carbon::parse('2000-01-01 00:50:32')->diffForHumans('@946684800');  // 50 minutes after

echo Carbon::create(2018, 2, 26, 4, 29, 43)->longRelativeDiffForHumans(Carbon::create(2016, 6, 21, 0, 0, 0), 6); // 1 year 8 months 5 days 4 hours 29 minutes 43 seconds after

You can also change the locale of the string using $date->locale('fr') before the diffForHumans() call. See the localization section for more detail.

Since 2.9.0 diffForHumans() parameters can be passed as an array:

echo Carbon::now()->diffForHumans(['options' => 0]); // 0 seconds ago
echo "\n";
// default options:
echo Carbon::now()->diffForHumans(['options' => Carbon::NO_ZERO_DIFF]); // 1 second ago
echo "\n";
echo Carbon::now()->diffForHumans(['options' => Carbon::JUST_NOW]); // just now
echo "\n";
echo Carbon::now()->subDay()->diffForHumans(['options' => 0]); // 1 day ago
echo "\n";
echo Carbon::now()->subDay()->diffForHumans(['options' => Carbon::ONE_DAY_WORDS]); // yesterday
echo "\n";
echo Carbon::now()->subDays(2)->diffForHumans(['options' => 0]); // 2 days ago
echo "\n";
echo Carbon::now()->subDays(2)->diffForHumans(['options' => Carbon::TWO_DAY_WORDS]); // before yesterday
echo "\n";

// Options can be combined with pipes
$now = Carbon::now();

echo $now->diffForHumans(['options' => Carbon::JUST_NOW | Carbon::ONE_DAY_WORDS | Carbon::TWO_DAY_WORDS]); // just now
echo "\n";

// Reference date for differences is `now` but you can use any other date (string, DateTime or Carbon instance):
$yesterday = $now->copy()->subDay();
echo $now->diffForHumans($yesterday); // 1 day after
echo "\n";
// By default differences methods produce "ago"/"from now" syntax using default reference (now),
// and "after"/"before" with other references
// But you can customize the syntax:
echo $now->diffForHumans($yesterday, ['syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW]); // 1 day from now
echo "\n";
echo $now->diffForHumans($yesterday, ['syntax' => 0]); // 1 day after
echo "\n";
echo $yesterday->diffForHumans(['syntax' => CarbonInterface::DIFF_ABSOLUTE]); // 1 day
echo "\n";
// Combined with options:
echo $now->diffForHumans($yesterday, [
    'syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW,
    'options' => Carbon::JUST_NOW | Carbon::ONE_DAY_WORDS | Carbon::TWO_DAY_WORDS,
]); // tomorrow
echo "\n";

// Other parameters:
echo $now->copy()->subHours(5)->subMinutes(30)->subSeconds(10)->diffForHumans([
    'parts' => 2,
]); // 5 hours 30 minutes ago
echo "\n";
echo $now->copy()->subHours(5)->subMinutes(30)->subSeconds(10)->diffForHumans([
    'parts' => 3, // Use -1 or INF for no limit
]); // 5 hours 30 minutes 10 seconds ago
echo "\n";
echo $now->copy()->subHours(5)->subMinutes(30)->subSeconds(10)->diffForHumans([
    'parts' => 3,
    'join' => ', ', // join with commas
]); // 5 hours, 30 minutes, 10 seconds ago
echo "\n";
echo $now->copy()->subHours(5)->subMinutes(30)->subSeconds(10)->diffForHumans([
    'parts' => 3,
    'join' => true, // join with natural syntax as per current locale
]); // 5 hours, 30 minutes and 10 seconds ago
echo "\n";
echo $now->copy()->subHours(5)->subMinutes(30)->subSeconds(10)->locale('fr')->diffForHumans([
    'parts' => 3,
    'join' => true, // join with natural syntax as per current locale
]); // il y a 5 heures, 30 minutes et 10 secondes
echo "\n";
echo $now->copy()->subHours(5)->subMinutes(30)->subSeconds(10)->diffForHumans([
    'parts' => 3,
    'short' => true, // short syntax as per current locale
]); // 5h 30m 10s ago
// 'aUnit' option added in 2.13.0 allows you to prefer "a day", "an hour", etc. over "1 day", "1 hour"
// for singular values when it's available in the current locale
echo $now->copy()->subHour()->diffForHumans([
    'aUnit' => true,
]); // an hour ago

// Before 2.9.0, you need to pass parameters as ordered parameters:
// ->diffForHumans($other, $syntax, $short, $parts, $options)
// and 'join' was not supported

If the argument is omitted or set to null, only Carbon::NO_ZERO_DIFF is enabled. Available options are:

  • Carbon::NO_ZERO_DIFF (enabled by default): turns empty diff into 1 second
  • Carbon::JUST_NOW disabled by default): turns diff from now to now into "just now"
  • Carbon::ONE_DAY_WORDS (disabled by default): turns "1 day from now/ago" to "yesterday/tomorrow"
  • Carbon::TWO_DAY_WORDS (disabled by default): turns "2 days from now/ago" to "before yesterday/after

Carbon::JUST_NOW, Carbon::ONE_DAY_WORDS and Carbon::TWO_DAY_WORDS are now only available with en and fr languages, other languages will fallback to previous behavior until missing translations are added.

Use the pipe operator to enable/disable multiple option at once, example: Carbon::ONE_DAY_WORDS | Carbon::TWO_DAY_WORDS

You also can use Carbon::enableHumanDiffOption($option), Carbon::disableHumanDiffOption($option), Carbon::setHumanDiffOptions($options) to change the default options and Carbon::getHumanDiffOptions() to get default options but you should avoid using it as being static it may conflict with calls from other code parts/third-party libraries.

Aliases and reverse methods are provided for semantic purpose:

  • from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) (alias of diffForHumans)
  • since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) (alias of diffForHumans)
  • to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) (inverse result, swap before and future diff)
  • until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) (alias of to)
  • fromNow($syntax = null, $short = false, $parts = 1, $options = null) (alias of from with first argument omitted unless the first argument is a DateTimeInterface, now used instead), for semantic usage: produce an "3 hours from now"-like string with dates in the future
  • ago($syntax = null, $short = false, $parts = 1, $options = null) (alias of fromNow), for semantic usage: produce an "3 hours ago"-like string with dates in the past
  • toNow($syntax = null, $short = false, $parts = 1, $options = null) (alias of to with first argument omitted, now used instead)
  • timespan($other = null, $timezone = null) calls diffForHumans with options join = ', ' (coma-separated), syntax = CarbonInterface::DIFF_ABSOLUTE (no "ago"/"from now"/"before"/"after" wording), options = CarbonInterface::NO_ZERO_DIFF (no "just now"/"yesterday"/"tomorrow" wording), parts = -1 (no limits) In this mode, you can't change options but you can pass an optional date to compare with or a string + timezone to parse to get this date.

Modifiers

These group of methods perform helpful modifications to the current instance. Most of them are self explanatory from their names... or at least should be. You'll also notice that the startOfXXX(), next() and previous() methods set the time to 00:00:00 and the endOfXXX() methods set the time to 23:59:59 for unit bigger than days.

The only one slightly different is the average() function. It moves your instance to the middle date between itself and the provided Carbon argument.

The powerful native modify() method of DateTime is available untouched. But we also provide an enhanced version of it: change() that allows some additional syntax like "next 3pm" and that is called internally by ->next() and ->previous().

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->startOfSecond()->format('s.u');          // 45.000000


$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->endOfSecond()->format('s.u');            // 45.999999

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->startOf('second')->format('s.u');        // 45.000000

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->endOf('second')->format('s.u');          // 45.999999
// ->startOf() and ->endOf() are dynamic equivalents to those methods

$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo $dt->startOfMinute();                         // 2012-01-31 15:32:00

$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo $dt->endOfMinute();                           // 2012-01-31 15:32:59

$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo $dt->startOfHour();                           // 2012-01-31 15:00:00

$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo $dt->endOfHour();                             // 2012-01-31 15:59:59

$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo Carbon::getMidDayAt();                        // 12
echo $dt->midDay();                                // 2012-01-31 12:00:00
Carbon::setMidDayAt(13);
echo Carbon::getMidDayAt();                        // 13
echo $dt->midDay();                                // 2012-01-31 13:00:00
Carbon::setMidDayAt(12);

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfDay();                            // 2012-01-31 00:00:00

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->endOfDay();                              // 2012-01-31 23:59:59

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfMonth();                          // 2012-01-01 00:00:00

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->endOfMonth();                            // 2012-01-31 23:59:59

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfYear();                           // 2012-01-01 00:00:00

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->endOfYear();                             // 2012-12-31 23:59:59

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfDecade();                         // 2010-01-01 00:00:00

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->endOfDecade();                           // 2019-12-31 23:59:59

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfCentury();                        // 2001-01-01 00:00:00

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->endOfCentury();                          // 2100-12-31 23:59:59

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfWeek();                           // 2012-01-30 00:00:00
var_dump($dt->dayOfWeek == Carbon::MONDAY);        // bool(true) : ISO8601 week starts on Monday

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->endOfWeek();                             // 2012-02-05 23:59:59
var_dump($dt->dayOfWeek == Carbon::SUNDAY);        // bool(true) : ISO8601 week ends on Sunday

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->next(Carbon::WEDNESDAY);                 // 2012-02-01 00:00:00
var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)
echo $dt->next('Wednesday');                       // 2012-02-08 00:00:00
echo $dt->next('04:00');                           // 2012-02-08 04:00:00
echo $dt->next('12:00');                           // 2012-02-08 12:00:00
echo $dt->next('04:00');                           // 2012-02-09 04:00:00

$dt = Carbon::create(2012, 1, 1, 12, 0, 0);
echo $dt->next();                                  // 2012-01-08 00:00:00

$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->previous(Carbon::WEDNESDAY);             // 2012-01-25 00:00:00
var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)

$dt = Carbon::create(2012, 1, 1, 12, 0, 0);
echo $dt->previous();                              // 2011-12-25 00:00:00

$start = Carbon::create(2014, 1, 1, 0, 0, 0);
$end = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $start->average($end);                        // 2014-01-15 12:00:00

echo Carbon::create(2014, 5, 30, 0, 0, 0)->firstOfMonth();                       // 2014-05-01 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->firstOfMonth(Carbon::MONDAY);         // 2014-05-05 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->lastOfMonth();                        // 2014-05-31 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->lastOfMonth(Carbon::TUESDAY);         // 2014-05-27 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfMonth(2, Carbon::SATURDAY);      // 2014-05-10 00:00:00

echo Carbon::create(2014, 5, 30, 0, 0, 0)->firstOfQuarter();                     // 2014-04-01 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->firstOfQuarter(Carbon::MONDAY);       // 2014-04-07 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->lastOfQuarter();                      // 2014-06-30 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->lastOfQuarter(Carbon::TUESDAY);       // 2014-06-24 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);    // 2014-04-12 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->startOfQuarter();                     // 2014-04-01 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->endOfQuarter();                       // 2014-06-30 23:59:59

echo Carbon::create(2014, 5, 30, 0, 0, 0)->firstOfYear();                        // 2014-01-01 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->firstOfYear(Carbon::MONDAY);          // 2014-01-06 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->lastOfYear();                         // 2014-12-31 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->lastOfYear(Carbon::TUESDAY);          // 2014-12-30 00:00:00
echo Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfYear(2, Carbon::SATURDAY);       // 2014-01-11 00:00:00

echo Carbon::create(2018, 2, 23, 0, 0, 0)->nextWeekday();                        // 2018-02-26 00:00:00
echo Carbon::create(2018, 2, 23, 0, 0, 0)->previousWeekday();                    // 2018-02-22 00:00:00
echo Carbon::create(2018, 2, 21, 0, 0, 0)->nextWeekendDay();                     // 2018-02-24 00:00:00
echo Carbon::create(2018, 2, 21, 0, 0, 0)->previousWeekendDay();                 // 2018-02-18 00:00:00

Rounding is also available for any unit:

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->roundMillisecond()->format('H:i:s.u');   // 15:32:45.654000

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->roundSecond()->format('H:i:s.u');        // 15:32:46.000000

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->floorSecond()->format('H:i:s.u');        // 15:32:45.000000

$dt = new Carbon('2012-01-31 15:32:15');
echo $dt->roundMinute()->format('H:i:s');          // 15:32:00

$dt = new Carbon('2012-01-31 15:32:15');
echo $dt->ceilMinute()->format('H:i:s');           // 15:33:00

// and so on up to millennia!

// precision rounding can be set, example: rounding to ten minutes
$dt = new Carbon('2012-01-31 15:32:15');
echo $dt->roundMinute(10)->format('H:i:s');        // 15:30:00

// and round, floor and ceil methods are shortcut for second rounding:
$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->round()->format('H:i:s.u');              // 15:32:46.000000
$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->floor()->format('H:i:s.u');              // 15:32:45.000000
$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->ceil()->format('H:i:s.u');               // 15:32:46.000000

// you can also pass the unit dynamically (and still precision as second argument):
$dt = new Carbon('2012-01-31');
echo $dt->roundUnit('month', 2)->format('Y-m-d');  // 2012-03-01
$dt = new Carbon('2012-01-31');
echo $dt->floorUnit('month')->format('Y-m-d');     // 2012-03-01
$dt = new Carbon('2012-01-31');
echo $dt->ceilUnit('month', 4)->format('Y-m-d');   // 2012-05-01

Constants

The following constants are defined in the Carbon class.

// These getters specifically return integers, ie intval()
var_dump(Carbon::SUNDAY);                          // int(0)
var_dump(Carbon::MONDAY);                          // int(1)
var_dump(Carbon::TUESDAY);                         // int(2)
var_dump(Carbon::WEDNESDAY);                       // int(3)
var_dump(Carbon::THURSDAY);                        // int(4)
var_dump(Carbon::FRIDAY);                          // int(5)
var_dump(Carbon::SATURDAY);                        // int(6)

var_dump(Carbon::YEARS_PER_CENTURY);               // int(100)
var_dump(Carbon::YEARS_PER_DECADE);                // int(10)
var_dump(Carbon::MONTHS_PER_YEAR);                 // int(12)
var_dump(Carbon::WEEKS_PER_YEAR);                  // int(52)
var_dump(Carbon::DAYS_PER_WEEK);                   // int(7)
var_dump(Carbon::HOURS_PER_DAY);                   // int(24)
var_dump(Carbon::MINUTES_PER_HOUR);                // int(60)
var_dump(Carbon::SECONDS_PER_MINUTE);              // int(60)

$dt = Carbon::createFromDate(2012, 10, 6);
if ($dt->dayOfWeek === Carbon::SATURDAY) {
    echo 'Place bets on Ottawa Senators Winning!';
}

Serialization

The Carbon instances can be serialized (including CarbonImmutable, CarbonInterval and CarbonPeriod).

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');

echo serialize($dt);                                              // O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}
// same as:
echo $dt->serialize();                                            // O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}

$dt = 'O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}';

echo unserialize($dt)->format('Y-m-d\TH:i:s.uP T');               // 2012-12-25T20:30:00.000000+04:00 MSK
// same as:
echo Carbon::fromSerialized($dt)->format('Y-m-d\TH:i:s.uP T');    // 2012-12-25T20:30:00.000000+04:00 MSK

JSON

The Carbon instances can be encoded to and decoded from JSON. Since the version 2.4, we explicitly require the PHP JSON extension. It should have no impact as this extension is bundled by default with PHP. If the extension is disabled, be aware you will be locked on 2.3. But you still can use --ignore-platform-reqs on composer update/install to upgrade then polyfill the missing JsonSerializable interface by including JsonSerializable.php.

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');
echo json_encode($dt);
// "2012-12-25T16:30:00.000000Z"

$json = '{"date":"2012-12-25 20:30:00.000000","timezone_type":3,"timezone":"Europe\/Moscow"}';
$dt = Carbon::__set_state(json_decode($json, true));
echo $dt->format('Y-m-d\TH:i:s.uP T');
// 2012-12-25T20:30:00.000000+04:00 MSK

You can use serializeUsing() to customize the serialization.

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow')->settings([
    'toJsonFormat' => function ($date) {
        return $date->getTimestamp();
    },
]);
echo json_encode($dt); // 1356453000

If you wan to apply this globally, first consider using factory, else or i you use Carbon 1 you can use:

$dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');
Carbon::serializeUsing(function ($date) {
    return $date->valueOf();
});
echo json_encode($dt); // 1356453000000

// Call serializeUsing with null to reset the serializer:
Carbon::serializeUsing(null);

The jsonSerialize() method allow you to call the function given to Carbon::serializeUsing() or the result of toJson() if no custom serialization specified.

Macro

You may be familiar with the macro concept if you are used to working with Laravel and objects such as response or collections. The Carbon macro() works the exact same way as the Laravel MacroableTrait one, it takes a method name as first argument and a closure as second. This will make the closure action available on all Carbon instances (and also as a Carbon static method) as a method with the given name.

Carbon::macro('diffFromYear', function ($year, $absolute = false, $short = false, $parts = 1) {
    return $this->diffForHumans(Carbon::create($year, 1, 1, 0, 0, 0), $absolute, $short, $parts);
});

echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019);                 // 1 year after
echo "\n";
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019, true);           // 1 year
echo "\n";
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019, true, true);     // 1yr
echo "\n";
echo Carbon::parse('2020-01-12 12:00:00')->diffFromYear(2019, true, true, 5);  // 1yr 1w 4d 12h

The sad part is IDE will not natively your macro method (no auto-completion for the method diffFromYear in the example above). But it's no longer a problem thanks to our CLI tool: carbon-cli that allow you to generate IDE helper files for your mixins and macros.

Macros are the perfect tool to output dates with some settings or user preferences.

// Let assume you get user settings from the browser or preferences stored in a database
$userTimezone = 'Europe/Paris';
$userLanguage = 'fr_FR';

Carbon::macro('formatForUser', function () use ($userTimezone, $userLanguage) {
    $date = $this->copy()->tz($userTimezone)->locale($userLanguage);

    return $date->calendar(); // or ->isoFormat($customFormat), ->diffForHumans(), etc.
});

// Then let assume you store all your dates/times in UTC (because you definitely should)
$dateString = '2010-01-23 10:00:00'; // Get this from your database or any input

// Then now you can easily display any date in a page/e-mail using those user settings and the chosen format
echo Carbon::parse($dateString, 'UTC')->formatForUser();   // 23/01/2010
echo "\n";
echo Carbon::tomorrow()->formatForUser();                  // Demain Γ  02:00
echo "\n";
echo Carbon::now()->subDays(3)->formatForUser();           // mardi dernier Γ  17:17

Macros can also be grouped in classes and be applied with mixin()

Class BeerDayCarbonMixin
{
    public function nextBeerDay()
    {
        return function () {
            return $this->modify('next wednesday');
        };
    }

    public function previousBeerDay()
    {
        return function () {
            return $this->modify('previous wednesday');
        };
    }
}

Carbon::mixin(new BeerDayCarbonMixin());

$date = Carbon::parse('First saturday of December 2018');

echo $date->previousBeerDay();                                                 // 2018-11-28 00:00:00
echo "\n";
echo $date->nextBeerDay();                                                     // 2018-12-05 00:00:00

You can check if a macro (mixin included) is available with hasMacro()

var_dump(Carbon::hasMacro('previousBeerDay'));                                 // bool(true)
var_dump(Carbon::hasMacro('diffFromYear'));                                    // bool(true)
echo "\n";
var_dump(Carbon::hasMacro('dontKnowWhat'));                                    // bool(false)

A macro starting with get followed by an uppercase letter will automatically provide a dynamic getter whilst a macro starting with set and followed by an uppercase letter will provide a dynamic setter:

// Let's say a school year starts 5 months before the start of the year, so the school year of 2018 actually begins in August 2017 and ends in July 2018,
// Then you can create get/set method this way:
Carbon::macro('setSchoolYear', function ($schoolYear) {
    $this->year = $schoolYear;
    if ($this->month > 7) {
        $this->year--;
    }
});
Carbon::macro('getSchoolYear', function () {
    $schoolYear = $this->year;
    if ($this->month > 7) {
        $schoolYear++;
    }

return $schoolYear;
});
// This will make getSchoolYear/setSchoolYear as usual, but get/set prefix will also enable
// the getter and setter methods for the ->schoolYear property.

$date = Carbon::parse('2016-06-01');

var_dump($date->schoolYear);                   // int(2016)
$date->addMonths(3);
var_dump($date->schoolYear);                   // int(2017)
$date->schoolYear++;
var_dump($date->format('Y-m-d'));              // string(10) "2017-09-01"
$date->schoolYear = 2020;
var_dump($date->format('Y-m-d'));              // string(10) "2019-09-01"

You can also intercept any other call with generic macro:

Carbon::genericMacro(function ($method) {
    // As an example we will convert firstMondayOfDecember into first Monday Of December to get strings that
    // DateTime can parse.
    $time = preg_replace('/[A-Z]/', ' $0', $method);

    try {
        // isset($this) means called dynamically like ->myMacro()
        if (isset($this)) {
            return $this->modify($time);
        }

        // else means called statically like ::myMacro()
        return new static($time);
    } catch (\Throwable $exception) {
        if (stripos($exception->getMessage(), 'Failed to parse') !== false) {
            // When trowhing BadMethodCallException from inside a generic macro will go to next generic macro
            // if there are other registered.
            throw new \BadMethodCallException('Try next macro', 0, $exception);
        }

        // Other exceptions thrown will not be caught
        throw $exception;
    }
}, 1 /* you can optionally pass a priority as a second argument, 0 by default, can be negative, higher priority ran first */);
// Generic macro get the asked method name as first argument, and method arguments as others.
// They can return any value.
// They can be added via "genericMacros" setting and this setting has precedence over statically declared generic macros.

$date = Carbon::parse('2016-06-01');

echo $date->nextSunday();                  // 2016-06-05 00:00:00
echo "\n";
echo $date->lastMondayOfPreviousMonth();   // 2016-05-30 00:00:00
Carbon::resetMacros(); // resetMacros remove all macros and generic macro declared statically

And guess what? all macro methods are also available on CarbonInterval and CarbonPeriod classes.

CarbonInterval::macro('twice', function () {
    return $this->times(2);
});
echo CarbonInterval::day()->twice()->forHumans(); // 2 days
$interval = CarbonInterval::hours(2)->minutes(15)->twice();
echo $interval->forHumans(['short' => true]); // 4h 30m

forHumans($syntax, $short, $parts, $options) allow the same option arguments as Carbon::diffForHumans() except $parts is set to -1 (no limit) by default.

CarbonPeriod::macro('countWeekdays', function () {
    return $this->filter('isWeekday')->count();
});
echo CarbonPeriod::create('2017-11-01', '2017-11-30')->countWeekdays();  // 22
echo CarbonPeriod::create('2017-12-01', '2017-12-31')->countWeekdays();  // 21

Check cmixin/business-time (that includes cmixin/business-day) to handle both holidays and business opening hours with a lot of advanced features.

Class CurrentDaysCarbonMixin
{
    /**
     * Get the all dates of week
     *
     * @return array
     */
    public static function getCurrentWeekDays()
    {
        return function () {
            $startOfWeek = (isset($this) ? $this : static::now())->startOfWeek()->subDay();
            $weekDays = [];

            for ($i = 0; $i < static::DAYS_PER_WEEK; $i++) {
                $weekDays[] = $startOfWeek->addDay()->startOfDay()->copy();
            }

            return $weekDays;
        };
    }

    /**
     * Get the all dates of month
     *
     * @return array
     */
    public static function getCurrentMonthDays()
    {
        return function () {
            $startOfMonth = (isset($this) ? $this : static::now())->startOfMonth()->subDay();
            $endOfMonth = (isset($this) ? $this : static::now())->endOfMonth()->format('d');
            $monthDays = [];

            for ($i = 0; $i < $endOfMonth; $i++)
            {
                $monthDays[] = $startOfMonth->addDay()->startOfDay()->copy();
            }

            return $monthDays;
        };
    }
}

Carbon::mixin(new CurrentDaysCarbonMixin());

function dumpDateList($dates) {
    echo substr(implode(', ', $dates), 0, 100).'...';
}

dumpDateList(Carbon::getCurrentWeekDays());                       // 2019-08-05 00:00:00, 2019-08-06 00:00:00, 2019-08-07 00:00:00, 2019-08-08 00:00:00, 2019-08-09 00:00...
dumpDateList(Carbon::getCurrentMonthDays());                      // 2019-08-01 00:00:00, 2019-08-02 00:00:00, 2019-08-03 00:00:00, 2019-08-04 00:00:00, 2019-08-05 00:00...
dumpDateList(Carbon::now()->subMonth()->getCurrentWeekDays());    // 2019-07-08 00:00:00, 2019-07-09 00:00:00, 2019-07-10 00:00:00, 2019-07-11 00:00:00, 2019-07-12 00:00...
dumpDateList(Carbon::now()->subMonth()->getCurrentMonthDays());   // 2019-07-01 00:00:00, 2019-07-02 00:00:00, 2019-07-03 00:00:00, 2019-07-04 00:00:00, 2019-07-05 00:00...

Credit: meteguerlek (#1191).

Carbon::macro('toAtomStringWithNoTimezone', function () {
    return $this->format('Y-m-d\TH:i:s');
});
echo Carbon::parse('2021-06-16 20:08:34')->toAtomStringWithNoTimezone(); // 2021-06-16T20:08:34

Credit: afrojuju1 (#1063).

Carbon::macro('easterDate', function ($year) {
    return Carbon::createMidnightDate($year, 3, 21)->addDays(easter_days($year));
});
echo Carbon::easterDate(2015)->format('d/m'); // 05/04
echo Carbon::easterDate(2016)->format('d/m'); // 27/03
echo Carbon::easterDate(2017)->format('d/m'); // 16/04
echo Carbon::easterDate(2018)->format('d/m'); // 01/04
echo Carbon::easterDate(2019)->format('d/m'); // 21/04

Credit: andreisena, 36864 (#1052).

Check cmixin/business-day for a more complete holidays handler.

Carbon::macro('datePeriod', function ($startDate, $endDate) {
    return new DatePeriod($startDate, new DateInterval('P1D'), $endDate);
});
foreach (Carbon::datePeriod(Carbon::createMidnightDate(2019, 3, 28), Carbon::createMidnightDate(2019, 4, 3)) as $date) {
    echo "$date\n";
}
/*
2019-03-28 00:00:00
2019-03-29 00:00:00
2019-03-30 00:00:00
2019-03-31 00:00:00
2019-04-01 00:00:00
2019-04-02 00:00:00
*/

Credit: reinink (#132).

class UserTimezoneCarbonMixin
{
    public $userTimeZone;

    /**
     * Set user timezone, will be used before format function to apply current user timezone
     *
     * @param $timezone
     */
    public function setUserTimezone()
    {
        $mixin = $this;

        return function ($timezone) use ($mixin) {
            $mixin->userTimeZone = $timezone;
        };
    }

    /**
     * Returns date formatted according to given format.
     *
     * @param string $format
     *
     * @return string
     *
     * @link http://php.net/manual/en/datetime.format.php
     */
    public function tzFormat()
    {
        $mixin = $this;

        return function ($format) use ($mixin) {
            if (!is_null($mixin->userTimeZone)) {
                $this->timezone($mixin->userTimeZone);
            }

            return $this->format($format);
        };
    }
}

Carbon::mixin(new UserTimezoneCarbonMixin());

Carbon::setUserTimezone('Europe/Berlin');
echo Carbon::createFromTime(12, 0, 0, 'UTC')->tzFormat('H:i'); // 14:00
echo Carbon::createFromTime(15, 0, 0, 'UTC')->tzFormat('H:i'); // 17:00
Carbon::setUserTimezone('America/Toronto');
echo Carbon::createFromTime(12, 0, 0, 'UTC')->tzFormat('H:i'); // 08:00
echo Carbon::createFromTime(15, 0, 0, 'UTC')->tzFormat('H:i'); // 11:00

Credit: thiagocordeiro (#927).

Whilst using a macro is the recommended way to add new methods or behaviour to Carbon, you can go further and extend the class itself which allows some alternative ways to override the primary methods; parse, format and createFromFormat.

class MyDateClass extends Carbon
{
    protected static $formatFunction = 'translatedFormat';

    protected static $createFromFormatFunction = 'createFromLocaleFormat';

    protected static $parseFunction = 'myCustomParse';

    public static function myCustomParse($string)
    {
        return static::rawCreateFromFormat('d m Y', $string);
    }
}

$date = MyDateClass::parse('20 12 2001')->locale('de');
echo $date->format('jS F y');            // 20. Dezember 01
echo "\n";

$date = MyDateClass::createFromFormat('j F Y', 'pt', '20 fevereiro 2001')->locale('pt');

echo $date->format('d/m/Y');             // 20/02/2001
echo "\n";

// Note than you can still access native methods using rawParse, rawFormat and rawCreateFromFormat:
$date = MyDateClass::rawCreateFromFormat('j F Y', '20 February 2001', 'UTC')->locale('pt');

echo $date->rawFormat('jS F y');         // 20th February 01
echo "\n";

$date = MyDateClass::rawParse('2001-02-01', 'UTC')->locale('pt');

echo $date->format('jS F y');            // 1ΒΊ fevereiro 01
echo "\n";

CarbonInterval

The CarbonInterval class is inherited from the PHP DateInterval class.

<?php
class CarbonInterval extends \DateInterval
{
    // code here
}

You can create an instance in the following ways:

echo CarbonInterval::year();                           // 1 year
echo "\n";
echo CarbonInterval::months(3);                        // 3 months
echo "\n";
echo CarbonInterval::days(3)->seconds(32);             // 3 days 32 seconds
echo "\n";
echo CarbonInterval::weeks(3);                         // 3 weeks
echo "\n";
echo CarbonInterval::days(23);                         // 3 weeks 2 days
echo "\n";
// years, months, weeks, days, hours, minutes, seconds, microseconds
echo CarbonInterval::create(2, 0, 5, 1, 1, 2, 7, 123); // 2 years 5 weeks 1 day 1 hour 2 minutes 7 seconds
echo "\n";
echo CarbonInterval::createFromDateString('3 months'); // 3 months

If you find yourself inheriting a \DateInterval instance from another library, fear not! You can create a CarbonInterval instance via a friendly instance() function.

$di = new \DateInterval('P1Y2M'); // <== instance from another API
$ci = CarbonInterval::instance($di);
echo get_class($ci);                                   // 'Carbon\CarbonInterval'
echo $ci;                                              // 1 year 2 months

And as the opposite you can extract a raw DateInterval from CarbonInterval and even cast it in any class that extends DateInterval

$ci = CarbonInterval::days(2);
$di = $ci->toDateInterval();
echo get_class($di);   // 'DateInterval'
echo $di->d;           // 2

// Your custom class can also extends CarbonInterval
class CustomDateInterval extends \DateInterval {}

$di = $ci->cast(\CustomDateInterval::class);
echo get_class($di);   // 'CustomDateInterval'
echo $di->d;           // 2

You can compare intervals the same way than Carbon objects, using equalTo(), notEqualTo() lessThan(), lessThanOrEqualTo(), greaterThan(), greaterThanOrEqualTo(), between(), betweenExcluded(), etc.

Other helpers, but beware the implementation provides helpers to handle weeks but only days are saved. Weeks are calculated based on the total days of the current instance.

echo CarbonInterval::year()->years;                    // 1
echo CarbonInterval::year()->dayz;                     // 0
echo CarbonInterval::days(24)->dayz;                   // 24
echo CarbonInterval::days(24)->daysExcludeWeeks;       // 3
echo CarbonInterval::weeks(3)->days(14)->weeks;        // 2  <-- days setter overwrites the current value
echo CarbonInterval::weeks(3)->weeks;                  // 3
echo CarbonInterval::minutes(3)->weeksAndDays(2, 5);   // 2 weeks 5 days 3 minutes

CarbonInterval extends DateInterval and you can create both using ISO-8601 duration format:

$ci = CarbonInterval::create('P1Y2M3D');
var_dump($ci->isEmpty()); // bool(false)
$ci = new CarbonInterval('PT0S');
var_dump($ci->isEmpty()); // bool(true)

Carbon intervals can be created from human-friendly strings thanks to fromString() method.

CarbonInterval::fromString('2 minutes 15 seconds');
CarbonInterval::fromString('2m 15s'); // or abbreviated

Note that month abbreviate "mo" to distinguish from minutes and the whole syntax is not case sensitive.

It also has a handy forHumans(), which is mapped as the __toString() implementation, that prints the interval for humans.

CarbonInterval::setLocale('fr');
echo CarbonInterval::create(2, 1)->forHumans();        // 2 ans 1 mois
echo CarbonInterval::hour()->seconds(3);               // 1 heure 3 secondes
CarbonInterval::setLocale('en');

As you can see, you can change the locale of the string using CarbonInterval::setLocale('fr').

As for Carbon, you can use the make method to return a new instance of CarbonInterval from other interval or strings:

$dateInterval = new DateInterval('P2D');
$carbonInterval = CarbonInterval::month();
echo CarbonInterval::make($dateInterval)->forHumans();       // 2 days
echo CarbonInterval::make($carbonInterval)->forHumans();     // 1 month
echo CarbonInterval::make('PT3H')->forHumans();              // 3 hours
echo CarbonInterval::make('1h 15m')->forHumans();            // 1 hour 15 minutes
// forHumans has many options, since version 2.9.0, the recommended way is to pass them as an associative array:
echo CarbonInterval::make('1h 15m')->forHumans(['short' => true]); // 1h 15m
$interval = CarbonInterval::make('1h 15m 45s');
echo $interval->forHumans(['join' => true]);                 // 1 hour, 15 minutes and 45 seconds
$esInterval = CarbonInterval::make('1h 15m 45s');
echo $esInterval->forHumans(['join' => true]);               // 1 hour, 15 minutes and 45 seconds
echo $interval->forHumans(['join' => true, 'parts' => 2]);   // 1 hour and 15 minutes
echo $interval->forHumans(['join' => ' - ']);                // 1 hour - 15 minutes - 45 seconds

// Available syntax modes:
// ago/from now (translated in the current locale)
echo $interval->forHumans(['syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW]);      // 1 hour 15 minutes 45 seconds ago
// before/after (translated in the current locale)
echo $interval->forHumans(['syntax' => CarbonInterface::DIFF_RELATIVE_TO_OTHER]);    // 1 hour 15 minutes 45 seconds before
// default for intervals (no prefix/suffix):
echo $interval->forHumans(['syntax' => CarbonInterface::DIFF_ABSOLUTE]);             // 1 hour 15 minutes 45 seconds

// Available options:
// transform empty intervals into "just now":
echo CarbonInterval::hours(0)->forHumans([
    'options' => CarbonInterface::JUST_NOW,
    'syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW,
]); // just now
// transform empty intervals into "1 second":
echo CarbonInterval::hours(0)->forHumans([
    'options' => CarbonInterface::NO_ZERO_DIFF,
    'syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW,
]); // 1 second ago
// transform "1 day ago"/"1 day from now" into "yesterday"/"tomorrow":
echo CarbonInterval::day()->forHumans([
    'options' => CarbonInterface::ONE_DAY_WORDS,
    'syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW,
]); // 1 day ago
// transform "2 days ago"/"2 days from now" into "before yesterday"/"after tomorrow":
echo CarbonInterval::days(2)->forHumans([
    'options' => CarbonInterface::TWO_DAY_WORDS,
    'syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW,
]); // 2 days ago
// options can be piped:
echo CarbonInterval::days(2)->forHumans([
    'options' => CarbonInterface::ONE_DAY_WORDS | CarbonInterface::TWO_DAY_WORDS,
    'syntax' => CarbonInterface::DIFF_RELATIVE_TO_NOW,
]); // 2 days ago

// Before version 2.9.0, parameters could only be passed sequentially:
// $interval->forHumans($syntax, $short, $parts, $options)
// and join parameter was not available

The add, sub (or subtract), times, shares, multiply and divide methods allow to do proceed intervals calculations:

$interval = CarbonInterval::make('7h 55m');
$interval->add(CarbonInterval::make('17h 35m'));
$interval->subtract(10, 'minutes');
// add(), sub() and subtract() can take DateInterval, CarbonInterval, interval as string or 2 arguments factor and unit
$interval->times(3);
echo $interval->forHumans();                                       // 72 hours 240 minutes
echo "\n";
$interval->shares(7);
echo $interval->forHumans();                                       // 10 hours 34 minutes
echo "\n";
// As you can see add(), times() and shares() operate naively a rounded calculation on each unit

// You also can use multiply() of divide() to cascade units and get precise calculation:
echo CarbonInterval::make('19h 55m')->multiply(3)->forHumans();    // 2 days 11 hours 45 minutes
echo "\n";
echo CarbonInterval::make('19h 55m')->divide(3)->forHumans();      // 6 hours 38 minutes 20 seconds

You get pure calculation from your input unit by unit. To cascade minutes into hours, hours into days etc. Use the cascade method:

echo $interval->forHumans();             // 10 hours 34 minutes
echo $interval->cascade()->forHumans();  // 10 hours 34 minutes

Default factors are:

  • 1 minute = 60 seconds
  • 1 hour = 60 minutes
  • 1 day = 24 hour
  • 1 week = 7 days
  • 1 month = 4 weeks
  • 1 year = 12 months

CarbonIntervals do not carry context so they cannot be more precise (no DST, no leap year, no real month length or year length consideration). But you can completely customize those factors. For example to deal with work time logs:

$cascades = CarbonInterval::getCascadeFactors(); // save initial factors

CarbonInterval::setCascadeFactors([
    'minute' => [60, 'seconds'],
    'hour' => [60, 'minutes'],
    'day' => [8, 'hours'],
    'week' => [5, 'days'],
    // in this example the cascade won't go farther than week unit
]);

echo CarbonInterval::fromString('20h')->cascade()->forHumans();              // 2 days 4 hours
echo CarbonInterval::fromString('10d')->cascade()->forHumans();              // 2 weeks
echo CarbonInterval::fromString('3w 18d 53h 159m')->cascade()->forHumans();  // 7 weeks 4 days 7 hours 39 minutes

// You can see currently set factors with getFactor:
echo CarbonInterval::getFactor('minutes', /* per */ 'hour');                 // 60
echo CarbonInterval::getFactor('days', 'week');                              // 5

// And common factors can be get with short-cut methods:
echo CarbonInterval::getDaysPerWeek();                                       // 5
echo CarbonInterval::getHoursPerDay();                                       // 8
echo CarbonInterval::getMinutesPerHour();                                    // 60
echo CarbonInterval::getSecondsPerMinute();                                  // 60
echo CarbonInterval::getMillisecondsPerSecond();                             // 1000
echo CarbonInterval::getMicrosecondsPerMillisecond();                        // 1000

CarbonInterval::setCascadeFactors($cascades); // restore original factors

Is it possible to convert an interval into a given unit (using provided cascade factors).

echo CarbonInterval::days(3)->hours(5)->total('hours');    // 77
echo CarbonInterval::days(3)->hours(5)->totalHours;        // 77
echo CarbonInterval::months(6)->totalWeeks;                // 24
echo CarbonInterval::year()->totalDays;                    // 336

->total method and properties need cascaded intervals, if your interval can have overflow, cascade them before calling these feature:

echo CarbonInterval::minutes(1200)->cascade()->total('hours'); // 20
echo CarbonInterval::minutes(1200)->cascade()->totalHours; // 20

You can also get the ISO 8601 spec of the inverval with spec()

echo CarbonInterval::days(3)->hours(5)->spec(); // P3DT5H

It's also possible to get it from a DateInterval object since to the static helper:

echo CarbonInterval::getDateIntervalSpec(new DateInterval('P3DT6M10S')); // P3DT6M10S

List of date intervals can be sorted thanks to the compare() and compareDateIntervals() methods:

$halfDay = CarbonInterval::hours(12);
$oneDay = CarbonInterval::day();
$twoDay = CarbonInterval::days(2);

echo CarbonInterval::compareDateIntervals($oneDay, $oneDay);   // 0
echo $oneDay->compare($oneDay);                                // 0
echo CarbonInterval::compareDateIntervals($oneDay, $halfDay);  // 1
echo $oneDay->compare($halfDay);                               // 1
echo CarbonInterval::compareDateIntervals($oneDay, $twoDay);   // -1
echo $oneDay->compare($twoDay);                                // -1

$list = [$twoDay, $halfDay, $oneDay];
usort($list, ['Carbon\CarbonInterval', 'compareDateIntervals']);

echo implode(', ', $list);                                     // 12 hours, 1 day, 2 days

Last, a CarbonInterval instance can be converted into a CarbonPeriod instance by calling toPeriod() with complementary arguments.

I hear you ask what is a CarbonPeriod instance. Oh! Perfect transition to our next chapter.

CarbonPeriod

CarbonPeriod is a human-friendly version of the DatePeriod with many shortcuts.

// Create a new instance:
$period = new CarbonPeriod('2018-04-21', '3 days', '2018-04-27');
// Use static constructor:
$period = CarbonPeriod::create('2018-04-21', '3 days', '2018-04-27');
// Use the fluent setters:
$period = CarbonPeriod::since('2018-04-21')->days(3)->until('2018-04-27');
// Start from a CarbonInterval:
$period = CarbonInterval::days(3)->toPeriod('2018-04-21', '2018-04-27');
// toPeriod can also be called from a Carbon or CarbonImmutable instance:
$period = Carbon::parse('2018-04-21')->toPeriod('2018-04-27', '3 days'); // pass end and interval
// interval can be a string, a DateInterval or a CarbonInterval
// You also can pass 2 arguments: number an string:
$period = Carbon::parse('2018-04-21')->toPeriod('2018-04-27', 3, 'days');
// Same as above:
$period = Carbon::parse('2018-04-21')->range('2018-04-27', 3, 'days'); // Carbon::range is an alias of Carbon::toPeriod
// Still the same:
$period = Carbon::parse('2018-04-21')->daysUntil('2018-04-27', 3);
// By default daysUntil will use a 1-day interval:
$period = Carbon::parse('2018-04-21')->daysUntil('2018-04-27'); // same as CarbonPeriod::create('2018-04-21', '1 day', '2018-04-27')
/*
    microsUntil() or microsecondsUntil() provide the same feature for microseconds intervals
    millisUntil() or millisecondsUntil() provide the same feature for milliseconds intervals
    secondsUntil() provides the same feature for seconds intervals
    minutesUntil() provides the same feature for minutes intervals
    hoursUntil() provides the same feature for hours intervals
    weeksUntil() provides the same feature for weeks intervals
    monthsUntil() provides the same feature for months intervals
    quartersUntil() provides the same feature for quarters intervals
    yearsUntil() provides the same feature for years intervals
    decadesUntil() provides the same feature for decades intervals
    centuriesUntil() provides the same feature for centuries intervals
    millenniaUntil() provides the same feature for millennia intervals
*/

A CarbonPeriod can be constructed in a number of ways:

  • start date, end date and optional interval (by default 1 day),
  • start date, number of recurrences and optional interval,
  • an ISO 8601 interval specification,
  • from an other DatePeriod or CarbonPeriod using CarbonPeriod::instance($period).

Dates can be given as DateTime/Carbon instances, absolute strings like "2007-10-15 15:00" or relative strings, for example "next monday". Interval can be given as DateInterval/CarbonInterval instance, ISO 8601 interval specification like "P4D", or human readable string, for example "4 days".

Default constructor and create() methods are very forgiving in terms of argument types and order, so if you want to be more precise the fluent syntax is recommended. On the other hand you can pass dynamic array of values to createFromArray() which will do the job of constructing a new instance with the given array as a list of arguments.

CarbonPeriod implements the Iterator interface. It means that it can be passed directly to a foreach loop:

$period = CarbonPeriod::create('2018-04-21', '3 days', '2018-04-27');
foreach ($period as $key => $date) {
    if ($key) {
        echo ', ';
    }
    echo $date->format('m-d');
}
// 04-21, 04-24, 04-27
echo "\n";

// Here is what happens under the hood:
$period->rewind(); // restart the iteration
while ($period->valid()) { // check if current item is valid
    if ($period->key()) { // echo comma if current key is greater than 0
        echo ', ';
    }
    echo $period->current()->format('m-d'); // echo current date
    $period->next(); // move to the next item
}
// 04-21, 04-24, 04-27

Parameters can be modified during the iteration:

$period = CarbonPeriod::create('2018-04-29', 7);
$dates = [];
foreach ($period as $key => $date) {
    if ($key === 3) {
        $period->invert()->start($date); // invert() is an alias for invertDateInterval()
    }
    $dates[] = $date->format('m-d');
}

echo implode(', ', $dates); // 04-29, 04-30, 05-01, 05-02, 05-01, 04-30, 04-29

Just as DatePeriod, the CarbonPeriod supports ISO 8601 time interval specification.

Note that the native DatePeriod treats recurrences as a number of times to repeat the interval. Thus it will give one less result when the start date is excluded. Introduction of custom filters in CarbonPeriod made it even more difficult to know the number of results. For that reason we changed the implementation slightly, and recurrences are treated as an overall limit for number of returned dates.

// Possible options are: CarbonPeriod::EXCLUDE_START_DATE | CarbonPeriod::EXCLUDE_END_DATE
// Default value is 0 which will have the same effect as when no options are given.
$period = CarbonPeriod::createFromIso('R4/2012-07-01T00:00:00Z/P7D', CarbonPeriod::EXCLUDE_START_DATE);
$dates = [];
foreach ($period as $date) {
    $dates[] = $date->format('m-d');
}

echo implode(', ', $dates); // 07-08, 07-15, 07-22, 07-29

You can retrieve data from the period with variety of getters:

$period = CarbonPeriod::create('2010-05-06', '2010-05-25', CarbonPeriod::EXCLUDE_START_DATE);

$exclude = $period->getOptions() & CarbonPeriod::EXCLUDE_START_DATE;

echo $period->getStartDate();            // 2010-05-06 00:00:00
echo "\n";
echo $period->getEndDate();              // 2010-05-25 00:00:00
// Note than ->getEndDate() will return null when the end is not fixed.
// For example CarbonPeriod::since('2018-04-21')->times(3) use repetition, so we don't know the end before iteration.
// Then you can use ->calculateEnd() instead that will use getEndDate() if available and else will execute a complete
// iteration to calculate the end date.
echo "\n";
echo $period->getDateInterval();         // 1 day
echo "\n";
echo $exclude ? 'exclude' : 'include';   // exclude
echo "\n";

var_dump($period->isStartIncluded());    // bool(false)
echo "\n";
var_dump($period->isEndIncluded());      // bool(true)
echo "\n";
var_dump($period->isStartExcluded());    // bool(true)
echo "\n";
var_dump($period->isEndExcluded());      // bool(false)
echo "\n";

echo $period->getIncludedStartDate();    // 2010-05-07 00:00:00
// If start is included getIncludedStartDate() = getStartDate()
// If start is excluded getIncludedStartDate() = getStartDate() + 1 interval
echo "\n";
echo $period->getIncludedEndDate();      // 2010-05-25 00:00:00
// If end is included getIncludedEndDate() = getEndDate()
// If end is excluded getIncludedEndDate() = getEndDate() - 1 interval
// If end is null getIncludedEndDate() = calculateEnd(), it means the period is actually iterated to get the last date
echo "\n";

echo $period->toString();                // Every 1 day from 2010-05-06 to 2010-05-25
echo "\n";
echo $period; /*implicit toString*/      // Every 1 day from 2010-05-06 to 2010-05-25

Additional getters let you access the results as an array:

$period = CarbonPeriod::create('2010-05-11', '2010-05-13');

echo $period->count();                   // 3, equivalent to count($period)
echo "\n";
echo implode(', ', $period->toArray());  // 2010-05-11 00:00:00, 2010-05-12 00:00:00, 2010-05-13 00:00:00
echo "\n";
echo $period->first();                   // 2010-05-11 00:00:00
echo "\n";
echo $period->last();                    // 2010-05-13 00:00:00

Note that if you intend to work using the above functions it's a good idea to store the result of toArray() call to a variable and use it instead, because each call performs a full iteration internally.

To change the parameters you can use setter methods:

$period = CarbonPeriod::create('2010-05-01', '2010-05-14', CarbonPeriod::EXCLUDE_END_DATE);

$period->setStartDate('2010-05-11');
echo implode(', ', $period->toArray());  // 2010-05-11 00:00:00, 2010-05-12 00:00:00, 2010-05-13 00:00:00
echo "\n";

// Second argument can be optionally used to exclude the date from the results.
$period->setStartDate('2010-05-11', false);
$period->setEndDate('2010-05-14', true);
echo implode(', ', $period->toArray());  // 2010-05-12 00:00:00, 2010-05-13 00:00:00, 2010-05-14 00:00:00
echo "\n";

$period->setRecurrences(2);
echo implode(', ', $period->toArray());  // 2010-05-12 00:00:00, 2010-05-13 00:00:00
echo "\n";

$period->setDateInterval('PT12H');
echo implode(', ', $period->toArray());  // 2010-05-11 12:00:00, 2010-05-12 00:00:00

You can change options using setOptions() to replace all options but you also can change them separately:

$period = CarbonPeriod::create('2010-05-06', '2010-05-25');

var_dump($period->isStartExcluded());    // bool(false)
var_dump($period->isEndExcluded());      // bool(false)

$period->toggleOptions(CarbonPeriod::EXCLUDE_START_DATE, true); // true, false or nothing to invert the option
var_dump($period->isStartExcluded());    // bool(true)
var_dump($period->isEndExcluded());      // bool(false) (unchanged)

$period->excludeEndDate();               // specify false to include, true or omit to exclude
var_dump($period->isStartExcluded());    // bool(true) (unchanged)
var_dump($period->isEndExcluded());      // bool(true)

$period->excludeStartDate(false);        // specify false to include, true or omit to exclude
var_dump($period->isStartExcluded());    // bool(false)
var_dump($period->isEndExcluded());      // bool(true)

You can check 2 periods overlap or not:

$period = CarbonPeriod::create('2010-05-06', '2010-05-25');

var_dump($period->overlaps('2010-05-22', '2010-06-03'));   // bool(true)$period2 = CarbonPeriod::create('2010-05-22', '2010-05-24');
var_dump($period->overlaps($period2));                     // bool(true)

$period = CarbonPeriod::create('2010-05-06 12:00', '2010-05-25');
$start = Carbon::create('2010-05-06 05:00');
$end = Carbon::create('2010-05-06 11:59');
var_dump($period->overlaps($start, $end));                 // bool(false)

As mentioned earlier, per ISO 8601 specification, recurrences is a number of times the interval should be repeated. The native DatePeriod will thus vary the number of returned dates depending on the exclusion of the start date. Meanwhile CarbonPeriod being more forgiving in terms of input and allowing custom filters, treats recurrences as an overall limit for number of returned dates:

$period = CarbonPeriod::createFromIso('R4/2012-07-01T00:00:00Z/P7D');
$days = [];
foreach ($period as $date) {
    $days[] = $date->format('d');
}

echo $period->getRecurrences();          // 4
echo implode(', ', $days);               // 01, 08, 15, 22

$days = [];
$period->setRecurrences(3)->excludeStartDate();
foreach ($period as $date) {
    $days[] = $date->format('d');
}

echo $period->getRecurrences();          // 3
echo implode(', ', $days);               // 08, 15, 22

$days = [];
$period = CarbonPeriod::recurrences(3)->sinceNow();
foreach ($period as $date) {
    $days[] = $date->format('Y-m-d');
}

echo implode(', ', $days);               // 2019-08-09, 2019-08-10, 2019-08-11

Dates returned by the DatePeriod can be easily filtered. Filters can be used for example to skip certain dates or iterate only over working days or weekends. A filter function should return true to accept a date, false to skip it but continue searching or CarbonPeriod::END_ITERATION to end the iteration.

$period = CarbonPeriod::between('2000-01-01', '2000-01-15');
$weekendFilter = function ($date) {
    return $date->isWeekend();
};
$period->filter($weekendFilter);

$days = [];
foreach ($period as $date) {
    $days[] = $date->format('m-d');
}
echo implode(', ', $days);                         // 01-01, 01-02, 01-08, 01-09, 01-15

You also can skip one or more value(s) inside the loop.

$period = CarbonPeriod::between('2000-01-01', '2000-01-10');
$days = [];
foreach ($period as $date) {
    $day = $date->format('m-d');
    $days[] = $day;
    if ($day === '01-04') {
        $period->skip(3);
    }
}
echo implode(', ', $days);                         // 01-01, 01-02, 01-03, 01-04, 01-08, 01-09, 01-10

getFilters() allow you to retrieve all the stored filters in a period. But be aware the recurrences limit and the end date will appear in the returned array as they are stored internally as filters.

$period = CarbonPeriod::end('2000-01-01')->recurrences(3);
var_export($period->getFilters());
/*
array (
  0 => 
  array (
    0 => 'Carbon\\CarbonPeriod::filterEndDate',
    1 => NULL,
  ),
  1 => 
  array (
    0 => 'Carbon\\CarbonPeriod::filterRecurrences',
    1 => NULL,
  ),
)
*/

Filters are stored in a stack and can be managed using a special set of methods:

$period = CarbonPeriod::between('2000-01-01', '2000-01-15');
$weekendFilter = function ($date) {
    return $date->isWeekend();
};

var_dump($period->hasFilter($weekendFilter));      // bool(false)
$period->addFilter($weekendFilter);
var_dump($period->hasFilter($weekendFilter));      // bool(true)
$period->removeFilter($weekendFilter);
var_dump($period->hasFilter($weekendFilter));      // bool(false)

// To avoid storing filters as variables you can name your filters:
$period->prependFilter(function ($date) {
    return $date->isWeekend();
}, 'weekend');

var_dump($period->hasFilter('weekend'));           // bool(true)
$period->removeFilter('weekend');
var_dump($period->hasFilter('weekend'));           // bool(false)

Order in which filters are added can have an impact on the performance and on the result, so you can use addFilter() to add a filter in the end of stack; and you can use prependFilter() to add one at the beginning. You can even use setFilters() to replace all filters. Note that you'll have to keep correct format of the stack and remember about internal filters for recurrences limit and end date. Alternatively you can use resetFilters() method and then add new filters one by one.

For example, when you add a custom filter that limits the number of attempted dates, the result will be different if you add it before or after the weekday filter.

// Note that you can pass a name of any Carbon method starting with "is", including macros
$period = CarbonPeriod::between('2018-05-03', '2018-05-25')->filter('isWeekday');

$attempts = 0;
$attemptsFilter = function () use (&$attempts) {
    return ++$attempts <= 5 ? true : CarbonPeriod::END_ITERATION;
};

$period->prependFilter($attemptsFilter, 'attempts');
$days = [];
foreach ($period as $date) {
    $days[] = $date->format('m-d');
}
echo implode(', ', $days);                         // 05-03, 05-04, 05-07

$attempts = 0;

$period->removeFilter($attemptsFilter)->addFilter($attemptsFilter, 'attempts');
$days = [];
foreach ($period as $date) {
    $days[] = $date->format('m-d');
}
echo implode(', ', $days);                         // 05-03, 05-04, 05-07, 05-08, 05-09

Note that the built-in recurrences filter doesn't work this way. It is instead based on the current key which is incremented only once per item, no matter how many dates have to be checked before a valid date is found. This trick makes it work the same both if you put it at the beginning or at the end of the stack.

A number of aliases has been added to simplify building the CarbonPeriod:

// "start", "since", "sinceNow":
CarbonPeriod::start('2017-03-10') == CarbonPeriod::create()->setStartDate('2017-03-10');
// Same with optional boolean argument $inclusive to change the option about include/exclude start date:
CarbonPeriod::start('2017-03-10', true) == CarbonPeriod::create()->setStartDate('2017-03-10', true);
// "end", "until", "untilNow":
CarbonPeriod::end('2017-03-20') == CarbonPeriod::create()->setEndDate('2017-03-20');
// Same with optional boolean argument $inclusive to change the option about include/exclude end date:
CarbonPeriod::end('2017-03-20', true) == CarbonPeriod::create()->setEndDate('2017-03-20', true);
// "dates", "between":
CarbonPeriod::dates(..., ...) == CarbonPeriod::create()->setDates(..., ...);
// "recurrences", "times":
CarbonPeriod::recurrences(5) == CarbonPeriod::create()->setRecurrences(5);
// "options":
CarbonPeriod::options(...) == CarbonPeriod::create()->setOptions(...);
// "toggle":
CarbonPeriod::toggle(..., true) == CarbonPeriod::create()->toggleOptions(..., true);
// "filter", "push":
CarbonPeriod::filter(...) == CarbonPeriod::create()->addFilter(...);
// "prepend":
CarbonPeriod::prepend(...) == CarbonPeriod::create()->prependFilter(...);
// "filters":
CarbonPeriod::filters(...) == CarbonPeriod::create()->setFilters(...);
// "interval", "each", "every", "step", "stepBy":
CarbonPeriod::interval(...) == CarbonPeriod::create()->setDateInterval(...);
// "invert":
CarbonPeriod::invert() == CarbonPeriod::create()->invertDateInterval();
// "year", "months", "month", "weeks", "week", "days", "dayz", "day",
// "hours", "hour", "minutes", "minute", "seconds", "second":
CarbonPeriod::hours(5) == CarbonPeriod::create()->setDateInterval(new CarbonInterval::hours(5));

CarbonPeriod can be easily converted to a human readable string and ISO 8601 specification:

$period = CarbonPeriod::create('2000-01-01 12:00', '3 days 12 hours', '2000-01-15 12:00');
echo $period->toString();            // Every 3 days and 12 hours from 2000-01-01 12:00:00 to 2000-01-15 12:00:00
echo "\n";
echo $period->toIso8601String();     // 2000-01-01T12:00:00+00:00/P3DT12H/2000-01-15T12:00:00+00:00

Period use and return Carbon instance by default, bu you can easily set/get the date class to use in order to get immutable dates for example or any class implementing CarbonInterface.

$period = new CarbonPeriod;
$period->setDateClass(CarbonImmutable::class);
$period->every('3 days 12 hours')->since('2000-01-01 12:00')->until('2000-01-15 12:00');

echo $period->getDateClass();              // Carbon\CarbonImmutable
echo "\n";
echo $period->getStartDate();              // 2000-01-01 12:00:00
echo "\n";
echo get_class($period->getStartDate());   // Carbon\CarbonImmutable

CarbonPeriod has forEach() and map() helper methods:

$period = CarbonPeriod::create('2018-04-21', '3 days', '2018-04-27');
$dates = $period->map(function (Carbon $date) {
    return $date->format('m-d');
});
// Or with PHP 7.4:
// $dates = $period->map(fn(Carbon $date) => $date->format('m-d'));
$array = iterator_to_array($dates); // $dates is a iterable \Generator
var_dump($array);
echo implode(', ', $array);
/*
array(3) {
  [0]=>
  string(5) "04-21"
  [1]=>
  string(5) "04-24"
  [2]=>
  string(5) "04-27"
}
04-21, 04-24, 04-27
*/
echo "\n";

// Here is what happens under the hood:
$period->forEach(function (Carbon $date) {
    echo $date->format('m-d')."\n";
});
/*
04-21
04-24
04-27
*/

As all other Carbon classes, CarbonPeriod has a cast() method to convert it:

$period = CarbonPeriod::create('2000-01-01 12:00', '3 days 12 hours', '2000-01-15 12:00');

// It would also works if your class extends DatePeriod
class MyPeriod extends CarbonPeriod {}

echo get_class($period->cast(MyPeriod::class)); // MyPeriod

// Shortcut to export as raw DatePeriod:
echo get_class($period->toDatePeriod());   // DatePeriod

You can check if periods follow themselves. Period A follows period B if the first iteration date of B equals to the last iteration date of A + the interval of A. For example [2019-02-01 => 2019-02-16] follows [2019-01-15 => 2019-01-31] (assuming neither start nor end are excluded via option for those period and assuming those period as a (1 day)-interval.

$a = CarbonPeriod::create('2019-01-15', '2019-01-31');
$b = CarbonPeriod::create('2019-02-01', '2019-02-16');

var_dump($b->follows($a));               // bool(true)
var_dump($a->isFollowedBy($b));          // bool(true)
// ->isConsecutiveWith($period) is true if it either ->follows($period) or ->isFollowedBy($period)
var_dump($b->isConsecutiveWith($a));     // bool(true)
var_dump($a->isConsecutiveWith($b));     // bool(true)

The contains() method allow you to check if a date is in the period range.

$period = CarbonPeriod::create('2019-01-15', '2019-01-31');

var_dump($period->contains('2019-01-22'));         // bool(true)

The comparison includes start and end unless you excluded them in the option and as for it concerns contains(), the exclusion only exclude the exact date, so:

$period = CarbonPeriod::create('2019-01-15', '2019-01-31', CarbonPeriod::EXCLUDE_END_DATE);

var_dump($period->contains('2019-01-31 00:00:00')); // bool(false)
var_dump($period->contains('2019-01-30 23:59:59')); // bool(true)

You can use start/end comparisons methods (that ignore exclusions) for more precise comparisons:

  • startsAt() start == date
  • startsBefore() start < date
  • startsBeforeOrAt() start <= date
  • startsAfter() start > date
  • startsAfterOrAt() start >= date
  • endsAt() end == date
  • endsBefore() end < date
  • endsBeforeOrAt() end <= date
  • endsAfter() end > date
  • endsAfterOrAt() end >= date
  • isStarted() start <= now
  • isEnded() end <= now
  • isInProgress() started but not ended

CarbonTimeZone

Starting with Carbon 2, timezones are now handled with a dedicated class CarbonTimeZone extending DateTimeZone.

$tz = new CarbonTimeZone('Europe/Zurich'); // instance way
$tz = CarbonTimeZone::create('Europe/Zurich'); // static way

// Get the original name of the timezone (can be region name or offset string):
echo $tz->getName();                 // Europe/Zurich
echo "\n";
// Casting a CarbonTimeZone to string will automatically call getName:
echo $tz;                            // Europe/Zurich
echo "\n";
echo $tz->getAbbreviatedName();      // bmt
echo "\n";
// With DST on:
echo $tz->getAbbreviatedName(true);  // cest
echo "\n";
// Alias of getAbbreviatedName:
echo $tz->getAbbr();                 // bmt
echo "\n";
echo $tz->getAbbr(true);             // cest
echo "\n";
// toRegionName returns the first matching region or false, if timezone was created with a region name,
// it will simply return this initial value.
echo $tz->toRegionName();            // Europe/Zurich
echo "\n";
// toOffsetName will give the current offset string for this timezone:
echo $tz->toOffsetName();            // +02:00
echo "\n";
// As with DST, this offset can change depending on the date, you may pass a date argument to specify it:
$winter = Carbon::parse('2018-01-01');
echo $tz->toOffsetName($winter);     // +01:00
echo "\n";
$summer = Carbon::parse('2018-07-01');
echo $tz->toOffsetName($summer);     // +02:00

// With no parameters, a default timezone is created:
echo new CarbonTimeZone();           // UTC
echo "\n";
echo CarbonTimeZone::create();       // UTC

The default timezone is given by date_default_timezone_get so it will be driven by the INI settings date.timezone but you really should override it at application level using date_default_timezone_set and you should set it to "UTC", if you're temped to or already use an other timezone as default, please read the following article: Always Use UTC Dates And Times.

It explains why UTC is a reliable standard. And this best-practice is even more important in PHP because the PHP DateTime API has many bugs with offsets changes and DST timezones. Some of them appeared on minor versions and even on patch versions (so you can get different results running the same code on PHP 7.1.7 and 7.1.8 for example) and some bugs are not even fixed yet. So we highly recommend to use UTC everywhere and only change the timezone when you want to display a date. See our first macro example.

While, region timezone ("Continent/City") can have DST and so have variable offset during the year, offset timezone have constant fixed offset:

$tz = CarbonTimeZone::create('+03:00'); // full string
$tz = CarbonTimeZone::create(3); // or hour integer short way

echo $tz->getName();                 // +03:00
echo "\n";
echo $tz;                            // +03:00
echo "\n";
// toRegionName will try to guess what region it could be:
echo $tz->toRegionName();            // Europe/Helsinki
echo "\n";
// to guess with DST off:
echo $tz->toRegionName(null, 0);     // Europe/Moscow
echo "\n";
// toOffsetName will give the initial offset no matter the date:
echo $tz->toOffsetName();            // +03:00
echo "\n";
echo $tz->toOffsetName($winter);     // +03:00
echo "\n";
echo $tz->toOffsetName($summer);     // +03:00

You also can convert region timezones to offset timezones and reciprocally.

$tz = new CarbonTimeZone(7);

echo $tz;                            // +07:00
echo "\n";
$tz = $tz->toRegionTimeZone();
echo $tz;                            // Asia/Novosibirsk
echo "\n";
$tz = $tz->toOffsetTimeZone();
echo $tz;                            // +07:00

You can create a CarbonTimeZone from mixed values using instance() method.

$tz = CarbonTimeZone::instance(new DateTimeZone('Europe/Paris'));

echo $tz;                            // Europe/Paris
echo "\n";

// Bad timezone will return false without strict mode
Carbon::useStrictMode(false);
$tz = CarbonTimeZone::instance('Europe/Chicago');
var_dump($tz);                       // bool(false)
echo "\n";

// or throw an exception using strict mode
Carbon::useStrictMode(true);
try {
    CarbonTimeZone::instance('Europe/Chicago');
} catch (InvalidArgumentException $exception) {
    $error = $exception->getMessage();
}
echo $error;                         // Unknown or bad timezone (Europe/Chicago)

// as some value cannot be dump as string in an error message or
// have unclear dump, you may pass a second argument to display
// instead in the errors
Carbon::useStrictMode(true);
try {
    $mixedValue = ['dummy', 'array'];
    CarbonTimeZone::instance($mixedValue, json_encode($mixedValue));
} catch (InvalidArgumentException $exception) {
    $error = $exception->getMessage();
}
echo $error;                         // Unknown or bad timezone (["dummy","array"])

Migrate to Carbon 2

If you plan to migrate from Carbon 1 to Carbon 2, please note the following breaking changes you should take care of.

  • Default values (when parameters are omitted) for $month and $day in the ::create() method are now 1 (were values from current date in Carbon 1). And default values for $hour, $minute and $second are now 0, this goes for omitted values, but you still can pass explicitly null to get the current value from now (similar behavior as in Carbon 1).
  • Now you get microsecond precision everywhere, it also means 2 dates in the same second but not in the same microsecond are no longer equal.
  • $date->jsonSerialize() and json_encode($date) no longer returns arrays but simple strings: "2017-06-27T13:14:15.000000Z". This allows to create dates from it easier in JavaScript. You still can get the previous behavior using:
    Carbon::serializeUsing(function ($date) {
        return [
            'date' => $date->toDateTimeString(),
            'timezone_type' => $date->timezone_type,
            'timezone' => $date->tzName,
        ];
    });
  • $date->setToStringFormat() with a closure no longer return a format but a final string. So you can return any string and the following in Carbon 1:
    Carbon::setToStringFormat(function ($date) {
        return $date->year === 1976 ?
            'jS \o\f F g:i:s a' :
            'jS \o\f F, Y g:i:s a';
    });
    would become in Carbon 2:
    Carbon::setToStringFormat(function ($date) {
        return $date->formatLocalized($date->year === 1976 ?
            'jS \o\f F g:i:s a' :
            'jS \o\f F, Y g:i:s a'
        );
    });
  • setWeekStartsAt and setWeekEndsAt no longer throw exceptions on values out of ranges, but they are also deprecated.
  • isSameMonth and isCurrentMonth now returns false for same month in different year but you can pass false as a second parameter of isSameMonth or first parameter of isCurrentMonth to compare ignoring the year.
  • ::compareYearWithMonth() and ::compareYearWithMonth() have been removed. Strict comparisons are now the default. And you can use the next parameter of isSame/isCurrent set to false to get month-only comparisons.
  • As we dropped PHP 5, $self is no longer needed in mixins you should just use $this instead.
  • As PHP 7.1+ perfectly supports microseconds, useMicrosecondsFallback and isMicrosecondsFallbackEnabled are no longer needed and so have been removed.
  • In Carbon 1, calls of an unknown method on CarbonInterval (ex: CarbonInterval::anything()) just returned null. Now they throw an exception.
  • In Carbon 1, dayOfYear started from 0. Now it starts from 1.
  • That's all folks! Every other methods you used in Carbon 1 should continue to work just the same with Carbon 2.