码迷,mamicode.com
首页 > 其他好文 > 详细

Carbon document

时间:2018-09-14 12:01:12      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:res   overload   mock   red   including   stat   error   range   chap   

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 modify it 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(9) "Tuesday 4"
var_dump($modifiedMutable->isoFormat(‘dddd D‘));     // string(9) "Tuesday 4"
// 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) "Monday 3"
var_dump($modifiedImmutable->isoFormat(‘dddd D‘));   // string(9) "Tuesday 4"
// 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 modifyformat or diff.

 

Now, let see how cool is this doc.

$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 it‘s split into 2 input and output pannels). You can also note a top right hand corner button allow you 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 \DateTimeZoneinstance. 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‘);

// or to create a date with a timezone of +1 to GMT during DST then just pass an integer
$date = Carbon::now(1);
echo $date->tzName;                      // Europe/London
echo "\n";

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

$date->utcOffset(180);

echo $date->tzName;                      // Europe/Helsinki
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;                               // 2018-09-03 15:40:44
echo "\n";
$today = Carbon::today();
echo $today;                             // 2018-09-03 00:00:00
echo "\n";
$tomorrow = Carbon::tomorrow(‘Europe/London‘);
echo $tomorrow;                          // 2018-09-04 00:00:00
echo "\n";
$yesterday = Carbon::yesterday();
echo $yesterday;                         // 2018-09-02 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(); }
// A two digit minute could not be found

 

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:40 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 oursection about partial microseconds support.

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, 64 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.

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 quelques secondes
echo "\n";
echo $date->monthName;           // septembre
echo "\n";
echo $date->isoFormat(‘LLLL‘);   // lundi 3 septembre 2018 15:40

 

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:40
*/

echo $notificationForJohn;
/*
Jun 15, 2018 12:34 PM
Today at 3:40 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‘);        // 03/09 9h Asia/Tokyo
echo "\n";
echo Carbon::today()->shiftTimezone(‘Asia/Tokyo‘)->format(‘d/m G\h e‘);      // 03/09 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

 

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

CodeExampleDescription
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:

Codeenfrjahr
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?nja 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?nja 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?nja 2017 17:04 
?et., 5. sij. 2017 17:04

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

 

$date = CarbonImmutable::now();
echo $date->calendar();                                      // Today at 3:40 PM
echo "\n";
echo $date->sub(‘1 day 3 hours‘)->calendar();                // Yesterday at 12:40 PM
echo "\n";
echo $date->sub(‘3 days 10 hours 23 minutes‘)->calendar();   // Last Friday at 5:17 AM
echo "\n";
echo $date->sub(‘8 days‘)->calendar();                       // 08/26/2018
echo "\n";
echo $date->add(‘1 day 3 hours‘)->calendar();                // Tomorrow at 6:40 PM
echo "\n";
echo $date->add(‘3 days 10 hours 23 minutes‘)->calendar();   // Friday at 2:03 AM
echo "\n";
echo $date->add(‘8 days‘)->calendar();                       // 09/11/2018
echo "\n";
echo $date->locale(‘fr‘)->calendar();                        // Aujourd’hui à 15:40

 

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

 

Here is an overview of the 102 locales (and 137 regional variants) supported by the last Carbon version:

LocaleDiff syntax1-day diff2-days diffShort unitsPeriod
af ? ? ? ? ?
ar ? ? ? ? ?
az ? ? ? ? ?
be ? ? ? ? ?
bg ? ? ? ? ?
bm ? ? ? ? ?
bn ? ? ? ? ?
bo ? ? ? ? ?
br ? ? ? ? ?
bs ? ? ? ? ?
ca ? ? ? ? ?
cs ? ? ? ? ?
cv ? ? ? ? ?
cy ? ? ? ? ?
da ? ? ? ? ?
de ? ? ? ? ?
dv ? ? ? ? ?
el ? ? ? ? ?
en ? ? ? ? ?
eo ? ? ? ? ?
es ? ? ? ? ?
et ? ? ? ? ?
eu ? ? ? ? ?
fa ? ? ? ? ?
fi ? ? ? ? ?
fo ? ? ? ? ?
fr ? ? ? ? ?
fy ? ? ? ? ?
gd ? ? ? ? ?
gl ? ? ? ? ?
gom ? ? ? ? ?
gu ? ? ? ? ?
he ? ? ? ? ?
hi ? ? ? ? ?
hr ? ? ? ? ?
hu ? ? ? ? ?
hy ? ? ? ? ?
id ? ? ? ? ?
is ? ? ? ? ?
it ? ? ? ? ?
ja ? ? ? ? ?
jv ? ? ? ? ?
ka ? ? ? ? ?
kk ? ? ? ? ?
km ? ? ? ? ?
kn ? ? ? ? ?
ko ? ? ? ? ?
ku ? ? ? ? ?
ky ? ? ? ? ?
lb ? ? ? ? ?
lo ? ? ? ? ?
lt ? ? ? ? ?
lv ? ? ? ? ?
me ? ? ? ? ?
mi ? ? ? ? ?
mk ? ? ? ? ?
ml ? ? ? ? ?
mn ? ? ? ? ?
mr ? ? ? ? ?
ms ? ? ? ? ?
mt ? ? ? ? ?
my ? ? ? ? ?
nb ? ? ? ? ?
ne ? ? ? ? ?
nl ? ? ? ? ?
nn ? ? ? ? ?
no ? ? ? ? ?
oc ? ? ? ? ?
pa ? ? ? ? ?
pl ? ? ? ? ?
ps ? ? ? ? ?
pt ? ? ? ? ?
ro ? ? ? ? ?
ru ? ? ? ? ?
sd ? ? ? ? ?
se ? ? ? ? ?
sh ? ? ? ? ?
si ? ? ? ? ?
sk ? ? ? ? ?
sl ? ? ? ? ?
sq ? ? ? ? ?
sr ? ? ? ? ?
ss ? ? ? ? ?
sv ? ? ? ? ?
sw ? ? ? ? ?
ta ? ? ? ? ?
te ? ? ? ? ?
tet ? ? ? ? ?
tg ? ? ? ? ?
th ? ? ? ? ?
tl ? ? ? ? ?
tlh ? ? ? ? ?
tr ? ? ? ? ?
tzl ? ? ? ? ?
tzm ? ? ? ? ?
ug ? ? ? ? ?
uk ? ? ? ? ?
ur ? ? ? ? ?
uz ? ? ? ? ?
vi ? ? ? ? ?
yo ? ? ? ? ?
zh ? ? ? ? ?

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

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

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();                                    // 2018-09-03 15:40:45

 

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(4) "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(43) 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)#361 (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)
var_dump(Carbon::now(‘Europe/London‘)->utc);                 // bool(false)
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(45)
// equivalent to:
var_dump(Carbon::now()->$unit);                              // int(45)
// If you have plural unit name, use singularUnit()
$unit = Carbon::singularUnit(‘seconds‘);
var_dump(Carbon::now()->get($unit));                         // int(45)
// 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) "2018-09-02 00:00"
var_dump($en->endOfWeek()->format(‘Y-m-d H:i‘));       // string(16) "2018-09-08 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) "2018-08-28 00:00"
var_dump($end->format(‘Y-m-d H:i‘));                   // string(16) "2018-09-03 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) "2018-09-01 00:00"
var_dump($ar->endOfWeek()->format(‘Y-m-d H:i‘));       // string(16) "2018-09-07 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 jugglingoccurs.

 

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 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

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)#367 (2) {
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(3) "UTC"
  }
}
*/

var_dump($dt->toObject());
/*
object(stdClass)#367 (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)#358 (2) {
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(3) "UTC"
  }
}
*/

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

 

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->eq($second));                     // bool(false)
var_dump($first->ne($second));                     // bool(true)
var_dump($first->gt($second));                     // bool(false)
var_dump($first->gte($second));                    // bool(false)
var_dump($first->lt($second));                     // bool(true)
var_dump($first->lte($second));                    // bool(true)

$first->setDateTime(2012, 1, 1, 0, 0, 0);
$second->setDateTime(2012, 1, 1, 0, 0, 0);         // Remember tz is ‘America/Vancouver‘

var_dump($first->eq($second));                     // bool(false)
var_dump($first->ne($second));                     // bool(true)
var_dump($first->gt($second));                     // bool(false)
var_dump($first->gte($second));                    // bool(false)
var_dump($first->lt($second));                     // bool(true)
var_dump($first->lte($second));                    // bool(true)

// All have verbose 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)

 

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

$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();                                  // 2018-09-03 15:40:45
echo $dt1->maximum();                              // 2018-09-03 15:40:45

$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->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 ismodify()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

// 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 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": false,
    "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*() 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

 

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->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)

 

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();                       // 3666
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, 31-Aug-18 00:00:00 UTC
echo $saturday->copy()->endOfWeek()->toRfc850String();       // Wednesday, 05-Sep-18 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, 27-Aug-18 00:00:00 UTC
echo $saturday->copy()->endOfWeek()->toRfc850String();       // Sunday, 02-Sep-18 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 agofrom now, etc : diffForHumans($other, CarbonInterface::DIFF_ABSOLUTE)CarbonInterface::DIFF_RELATIVE_TO_NOW to get modifiers agoor from nowCarbonInterface::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());   // 1 year 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();                      // 5 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.

Options can be passed as fifth argument of diffForHumans():

 

echo Carbon::now()->diffForHumans(null, null, false, 1, 0); // 0 seconds ago
echo "\n";
echo Carbon::now()->diffForHumans(null, null, false, 1, Carbon::NO_ZERO_DIFF); // 1 second ago
echo "\n";
echo Carbon::now()->diffForHumans(null, null, false, 1, Carbon::JUST_NOW); // just now
echo "\n";
echo Carbon::now()->subDay()->diffForHumans(null, null, false, 1, 0); // 1 day ago
echo "\n";
echo Carbon::now()->subDay()->diffForHumans(null, null, false, 1, Carbon::ONE_DAY_WORDS); // yesterday
echo "\n";
echo Carbon::now()->subDays(2)->diffForHumans(null, null, false, 1, 0); // 2 days ago
echo "\n";
echo Carbon::now()->subDays(2)->diffForHumans(null, null, false, 1, Carbon::TWO_DAY_WORDS); // before yesterday
echo "\n";

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

echo $date->diffForHumans(null, null, false, 1, Carbon::JUST_NOW | Carbon::ONE_DAY_WORDS | Carbon::TWO_DAY_WORDS); // just now

 

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, now used instead)
  • toNow($syntax = null, $short = false, $parts = 1, $options = null) (alias of to with first argument omitted, now used instead)

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.

 

$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)

$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.

 

$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 work with Laravel and objects such as response or collections. The Carbon macro() works the exact same way than the Laravel MacroableTrait one, it take a method name as first argument and a closure as second. This make the closure action available on all Carbon instance (and also as 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

 

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)

 

Macro starting with get followed by an uppercase letter will automatically provide a dynamic getter, and same for set providing a dynamic setter:

 

// Let say a school year start 5 months before, so school year 2018 is august 2017 to 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
// getter and setter 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 "\nn;
echo $date->lastMondayOfPreviousMonth();   // 2016-05-30 00:00:00

 

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(true);           // 4h 30m

 

forHumans($syntax, $short, $parts, $options) allow the same option arguments asCarbon::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

 

Here are some useful macros proposed by the community:

 

Carbon::macro(‘isHoliday‘, function () {
    return in_array($this->format(‘d/m‘), [
        ‘25/12‘, // Christmas
        ‘01/01‘, // New Year
        // ...
    ]);
});
var_dump(Carbon::createMidnightDate(2012, 12, 25)->isHoliday());  // bool(true)
var_dump(Carbon::createMidnightDate(2017, 6, 25)->isHoliday());   // bool(false)
var_dump(Carbon::createMidnightDate(2021, 1, 1)->isHoliday());    // bool(true)

 

Credit: kylekatarnls (#116).

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

 

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());                       // 2018-09-03 00:00:00, 2018-09-04 00:00:00, 2018-09-05 00:00:00, 2018-09-06 00:00:00, 2018-09-07 00:00...
dumpDateList(Carbon::getCurrentMonthDays());                      // 2018-09-01 00:00:00, 2018-09-02 00:00:00, 2018-09-03 00:00:00, 2018-09-04 00:00:00, 2018-09-05 00:00...
dumpDateList(Carbon::now()->subMonth()->getCurrentWeekDays());    // 2018-07-30 00:00:00, 2018-07-31 00:00:00, 2018-08-01 00:00:00, 2018-08-02 00:00:00, 2018-08-03 00:00...
dumpDateList(Carbon::now()->subMonth()->getCurrentMonthDays());   // 2018-08-01 00:00:00, 2018-08-02 00:00:00, 2018-08-03 00:00:00, 2018-08-04 00:00:00, 2018-08-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: andreisena36864 (#1052).

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

 

Carbon::macro(‘range‘, function ($startDate, $endDate) {
    return new DatePeriod($startDate, new DateInterval(‘P1D‘), $endDate);
});
foreach (Carbon::range(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).

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";
echo CarbonInterval::create(2, 0, 5, 1, 1, 2, 7);      // 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

 

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 un mois
echo CarbonInterval::hour()->seconds(3);               // une 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
// Pass true to get short format
echo CarbonInterval::make(‘1h 15m‘)->forHumans(true);        // 1h 15m

 

Natively DateInterval add and multiply units separately, so:

 

$interval = CarbonInterval::make(‘7h 55m‘);
$interval->add(CarbonInterval::make(‘17h 35m‘));
$interval->times(3);
echo $interval->forHumans(); // 72 hours 270 minutes

 

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();             // 72 hours 270 minutes
echo $interval->cascade()->forHumans();  // 3 days 4 hours 30 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

 

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‘);

 

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.

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
echo "\n";
echo $period->getDateInterval();         // 1 day
echo "\n";
echo $exclude ? ‘exclude‘ : ‘include‘;   // exclude
echo "\n";

var_dump($period->isStartExcluded());    // bool(true)
echo "\n";
var_dump($period->isEndExcluded());      // bool(false)
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)

 

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);               // 2018-09-03, 2018-09-04, 2018-09-05

 

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 useresetFilters() 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 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

 

Carbon document

标签:res   overload   mock   red   including   stat   error   range   chap   

原文地址:https://www.cnblogs.com/mouseleo/p/9645425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!