Академический Документы
Профессиональный Документы
Культура Документы
<?php
namespace Carbon;
Carbon has all of the functions inherited from the base DateTime class. This approach allows
you to access the base functionality if you see anything missing in Carbon but is there in
DateTime.
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 quali�ed name each time.
use Carbon\Carbon;
Note: I live in Ottawa, Ontario, Canada and if the timezone is not speci�ed in the
examples then the default of 'America/Toronto' is to be assumed. Typically
Ottawa is -0500 but when daylight savings time is on we are -0400.
Special care has been taken to ensure timezones are handled correctly, and where
appropriate are based on the underlying DateTime implementation. For example all
comparisons are done in UTC or in the timezone of the datetime being used.
echo $dtVancouver->diffInHours($dtToronto); // 3
Also is comparisons are done in the timezone of the provided Carbon instance. For example my
current timezone is -13 hours from Tokyo. So Carbon::now('Asia/Tokyo')->isToday() would only
return false for any time past 1 PM my time. This doesn't make sense since now() in tokyo is always
today in Tokyo. Thus the comparison to now() is done in the same timezone as the current instance.
Instantiation
There are several di�erent methods available to create a new instance of Carbon. First there
is a constructor. It overrides the parent constructor (http://www.php.net/manual
/en/datetime.construct.php) and you are best to read about the �rst parameter from the PHP
manual and understand the date/time string formats it accepts. You'll hopefully �nd yourself
rarely using the constructor but rather relying on the explicit static methods for improved
readability.
You'll notice above that the timezone (2nd) parameter was passed as a string and an integer
rather than a \DateTimeZone instance. All DateTimeZone parameters have been augmented
so you can pass a DateTimeZone instance, string or integer o�set 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();
// or to create a date with a timezone of +1 to GMT during DST then just pass an integer
echo Carbon::now(1)->tzName; // Europe/London
If you really love your �uid 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.
$now = Carbon::now();
echo $now; // 2016-06-24 15:18:34
$today = Carbon::today();
echo $today; // 2016-06-24 00:00:00
$tomorrow = Carbon::tomorrow('Europe/London');
echo $tomorrow; // 2016-06-25 00:00:00
$yesterday = Carbon::yesterday();
echo $yesterday; // 2016-06-23 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() (http://php.net/manual/en/datetime.getlasterrors.php) call.
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 for default values (mimicking the
underlying PHP library) occurs when an hour value is speci�ed but no minutes or seconds,
they will get defaulted to 0.
The �nal two create functions are for working with unix timestamps (http://en.wikipedia.org
/wiki/Unix_time). The �rst 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 di�erent in that the timezone will remain UTC (GMT). The
second acts the same as Carbon::createFromFormat('@'.$timestamp) but I have just
made it a little more explicit. Negative timestamps are also allowed.
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
Finally, if you �nd yourself inheriting a \DateTime instance from another library, fear not!
You can create a Carbon instance via a friendly instance() function.
$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
A quick note about microseconds. The PHP DateTime object allows you to set a microsecond
value but ignores it for all of its date math. As of 1.12.0 Carbon now supports microseconds
during instantiation or copy operations as well as by default with the format() method.
$dt = Carbon::parse('1975-05-21 22:23:00.123456');
echo $dt->micro; // 123456
echo $dt->copy()->micro; // 123456
Ever need to loop through some dates to �nd 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:
Localization
Unfortunately the base class DateTime does not have any localization support. To begin
localization support a formatLocalized($format) method was added. The implementation
makes a call to strftime (http://www.php.net/strftime) using the current instance timestamp.
If you �rst set the current locale with PHP function setlocale() (http://www.php.net/setlocale)
then the string returned will be formatted in the correct locale.
setlocale(LC_TIME, 'German');
echo $dt->formatLocalized('%A %d %B %Y'); // Mittwoch 21 Mai 1975
setlocale(LC_TIME, '');
echo $dt->formatLocalized('%A %d %B %Y'); // Wednesday 21 May 1975
diffForHumans() has also been localized. You can set the Carbon locale by using the static
Carbon::setLocale() function.
Carbon::setLocale('de');
echo Carbon::now()->addYear()->diffForHumans(); // in 1 Jahr
Carbon::setLocale('en');
on Linux
If you have trouble with translations, check locales installed in your system (local and
production).
locale -a to list locales enabled.
sudo locale-gen fr_FR.UTF-8 to install a new locale.
sudo dpkg-reconfigure locales to publish all locale enabled.
And reboot your system.
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 speci�cally under the
following conditions:
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 !
this
next
last
tomorrow
yesterday
+
-
�rst
last
ago
Be aware that similar to the next(), previous() and modify() methods some of these relative
modi�ers will set the time to 00:00:00.
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-9-5 23:26:11.123789');
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. Speci�cally, 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;
Fluent Setters
No arguments are optional for the setters, but there are enough variety in the function
de�nitions that you shouldn't need them anyway. 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. Speci�cally, setting the timestamp will not set the corresponding
timezone to UTC.
$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->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();
$dt->timestamp(169957925)->timezone('Europe/London');
$dt->tz('America/Toronto')->setTimezone('America/Vancouver');
IsSet
The PHP function __isset() is implemented. This was done as some external systems (ex.
Twig (http://twig.sensiolabs.org/doc/recipes.html#using-dynamic-object-properties)) 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() (http://www.php.net
/manual/en/language.oop5.overloading.php#object.isset), isset() (http://www.php.net
/manual/en/function.isset.php), empty() (http://www.php.net/manual
/en/function.empty.php).
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() (http://php.net/manual/en/datetime.format.php). You'll notice the
__toString() method is de�ned which allows a Carbon instance to be printed as a pretty
date time string when used in a string context.
You can also set the default __toString() format (which defaults to Y-m-d H:i:s ) thats used
when type juggling (http://php.net/manual/en/language.types.type-juggling.php) occurs.
$dt = Carbon::now();
Comparison
Simple comparison is o�ered 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; // America/Toronto
$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');
var_dump($first->eq($second)); // bool(true)
var_dump($first->ne($second)); // bool(false)
var_dump($first->gt($second)); // bool(false)
var_dump($first->gte($second)); // bool(true)
var_dump($first->lt($second)); // bool(false)
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)
To determine if the current instance is between two other instances you can use the aptly
named between() method. 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)
Woah! Did you forget min() and max() ? Nope. That is covered as well by the suitably named
min() and max() methods. As usual the default parameter is now if null is speci�ed.
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();
$dt->isWeekday();
$dt->isWeekend();
$dt->isYesterday();
$dt->isToday();
$dt->isTomorrow();
$dt->isFuture();
$dt->isPast();
$dt->isLeapYear();
$dt->isSameDay(Carbon::now());
$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!
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 ;)
Di�erence
These functions always return the total di�erence expressed in the speci�ed time requested.
This di�ers from the base class diff() function where an interval of 61 seconds would be
returned as 1 minute and 1 second via a DateInterval instance. The diffInMinutes()
function would simply return 1. All values are truncated and not rounded. Each function
below has a default �rst 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. The comparisons are done in UTC.
// Carbon::diffInYears(Carbon $dt = null, $abs = true)
echo Carbon::now('America/Vancouver')->diffInSeconds(Carbon::now('Europe/London')); // 0
echo $littleHandRotations; // 24
This method will add a phrase after the di�erence value relative to the instance and the
passed in instance. There are 4 possibilities:
You may also pass true as a 2nd parameter to remove the modi�ers ago, from now, etc :
diffForHumans(Carbon $other, true) .
Modi�ers
These group of methods perform helpful modi�cations 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.
The only one slightly di�erent is the average() function. It moves your instance to the
middle date between itself and the provided Carbon argument.
$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
echo $dt->startOfDay(); // 2012-01-31 00:00:00
Constants
The following constants are de�ned 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)
CarbonInterval
The Carbon class is inherited (http://php.net/manual/en/keyword.extends.php) from the PHP
DateInterval (http://php.net/manual/en/class.dateinterval.php) class.
<?php
class CarbonInterval extends \DateInterval
{
// code here
}
If you �nd yourself inheriting a \DateInterval instance from another library, fear not! You
can create a CarbonInterval instance via a friendly instance() function.
Other helpers, but beware the implemenation 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 va
echo CarbonInterval::weeks(3)->weeks; // 3
echo CarbonInterval::minutes(3)->weeksAndDays(2, 5); // 2 weeks 5 days 3 minutes
CarbonInterval::setLocale('fr');
echo CarbonInterval::create(2, 1)->forHumans(); // 2 ans 1 mois
echo CarbonInterval::hour()->seconds(3); // 1 heure 3 secondes
CarbonInterval::setLocale('en');
As you can see, you can change the locale of the string using
CarbonInterval::setLocale('fr') .