Skip to content

Latest commit

 

History

History
786 lines (585 loc) · 37.2 KB

readme.src.md

File metadata and controls

786 lines (585 loc) · 37.2 KB

This file is autogenerated. Please see the Contributing section from more information.

Carbon

Build Status

A simple API extension for DateTime with PHP 5.3+

{{::lint(
printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));  //implicit __toString()
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);

$officialDate = Carbon::now()->toRFC2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$worldWillEnd = Carbon::createFromDate(2012, 12, 21, 'GMT');

// Don't really want to die so mock now
Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));

// comparisons are always done in UTC
if (Carbon::now()->gte($worldWillEnd)) {
   die();
}

// Phew! Return to normal behaviour
Carbon::setTestNow();

if (Carbon::now()->isWeekend()) {
   echo 'Party!';
}
)}}
{{intro::exec(echo Carbon::now()->subMinutes(2)->diffForHumans();)}} // '{{intro_eval}}'

// ... but also does 'from now', 'after' and 'before'
// rolling up to seconds, minutes, hours, days, months, years

{{::lint(
$daysSinceEpoch = Carbon::createFromTimeStamp(0)->diffInDays();
)}}

README Contents

## Installation ### Requirements
  • Any flavour of PHP 5.3+ should do
  • [optional] PHPUnit to execute the test suite
### With Composer

The easiest way to install Carbon is via composer. Create the following composer.json file and run the php composer.phar install command to install it.

{
    "require": {
        "nesbot/Carbon": "*"
    }
}
<?php
require 'vendor/autoload.php';

use Carbon\Carbon;

{{::lint(printf("Now: %s", Carbon::now());)}}
### Without Composer

Why are you not using composer? Download Carbon.php from the repo and save the file into your project path somewhere.

<?php
require 'path/to/Carbon.php';

use Carbon\Carbon;

{{::lint(printf("Now: %s", Carbon::now());)}}
## API

The Carbon class is inherited from the PHP DateTime class.

<?php
class Carbon extends \DateTime
{
    // code here
}

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.

Note: I live in Ottawa, Ontario, Canada and if the timezone is not specified 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.

{{::lint($dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto');)}}
{{::lint($dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver');)}}

{{tz::exec(echo $dtVancouver->diffInHours($dtToronto);)}} // {{tz_eval}}

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

{{::lint($carbon = new Carbon();/*pad(40)*/)}} // equivalent to Carbon::now()
{{::lint($carbon = new Carbon('first day of January 2008', 'America/Vancouver');)}}
{{ctorType::exec(echo get_class($carbon);/*pad(40)*/)}} // '{{ctorType_eval}}'

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

{{::lint(
$now = Carbon::now();

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

// or just pass the timezone as a string
$nowInLondonTz = Carbon::now('Europe/London');
)}}

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.

{{parse1::exec(echo (new Carbon('first day of December 2008'))->addWeeks(2);/*pad(65)*/)}} // {{parse1_eval}}
{{parse2::exec(echo Carbon::parse('first day of December 2008')->addWeeks(2);/*pad(65)*/)}} // {{parse2_eval}}

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.

{{::lint($now = Carbon::now();)}}
{{now::exec(echo $now;/*pad(40)*/)}} // {{now_eval}}
{{::lint($today = Carbon::today();)}}
{{today::exec(echo $today;/*pad(40)*/)}} // {{today_eval}}
{{::lint($tomorrow = Carbon::tomorrow('Europe/London');)}}
{{tomorrow::exec(echo $tomorrow;/*pad(40)*/)}} // {{tomorrow_eval}}
{{::lint($yesterday = Carbon::yesterday();)}}
{{yesterday::exec(echo $yesterday;/*pad(40)*/)}} // {{yesterday_eval}}

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.

Carbon::createFromDate($year, $month, $day, $tz);
Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

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 specified but no minutes or seconds, they will get defaulted to 0.

{{::lint(
$xmasThisYear = Carbon::createFromDate(null, 12, 25);  // Year defaults to current year
$Y2K = Carbon::create(2000, 1, 1, 0, 0, 0);
$alsoY2K = Carbon::create(1999, 12, 31, 24);
$noonLondonTz = Carbon::createFromTime(12, 0, 0, 'Europe/London');
)}}

// {{createFromDateException_eval}}
{{createFromDateException::exec(try { Carbon::create(1975, 5, 21, 22, -2, 0); } catch(InvalidArgumentException $x) { echo $x->getMessage(); })}}
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. If you look at the source for the createXX() functions above, they all make a call to createFromFormat().

{{createFromFormat1::exec(echo Carbon::createFromFormat('Y-m-d H', '1975-05-21 22')->toDateTimeString();)}} // {{createFromFormat1_eval}}

The final two 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). The second acts the same as Carbon::createFromFormat('@'.$timestamp) but I have just made it a little more explicit. Negative timestamps are also allowed.

{{createFromTimeStamp1::exec(echo Carbon::createFromTimeStamp(-1)->toDateTimeString();/*pad(80)*/)}} // {{createFromTimeStamp1_eval}}
{{createFromTimeStamp2::exec(echo Carbon::createFromTimeStamp(-1, 'Europe/London')->toDateTimeString();/*pad(80)*/)}} // {{createFromTimeStamp2_eval}}
{{createFromTimeStampUTC::exec(echo Carbon::createFromTimeStampUTC(-1)->toDateTimeString();/*pad(80)*/)}} // {{createFromTimeStampUTC_eval}}

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.

{{::lint($dt = Carbon::now();)}}
{{copy2::exec(echo $dt->diffInYears($dt->copy()->addYear());)}}  // {{copy2_eval}}

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

Finally, if you find yourself inheriting a \DateTime instance from another library, fear not! You can create a Carbon instance via a friendly instance() function.

{{::lint($dt = new \DateTime('first day of January 2008');)}} // <== instance from another API
{{::lint($carbon = Carbon::instance($dt);)}}
{{ctorType1::exec(echo get_class($carbon);/*pad(54)*/)}} // '{{ctorType1_eval}}'
{{ctorType2::exec(echo $carbon->toDateTimeString();/*pad(54)*/)}} // {{ctorType2_eval}}
### 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')
{{::lint($knownDate = Carbon::create(2001, 5, 21, 12);/*pad(54)*/)}} // create testing date
{{::lint(Carbon::setTestNow($knownDate);/*pad(54)*/)}} // set the mock (of course this could be a real mock object)
{{testaid1::exec(echo Carbon::now();/*pad(54)*/)}} // {{testaid1_eval}}
{{testaid2::exec(echo new Carbon();/*pad(54)*/)}} // {{testaid2_eval}}
{{testaid3::exec(echo Carbon::parse();/*pad(54)*/)}} // {{testaid3_eval}}
{{testaid4::exec(echo new Carbon('now');/*pad(54)*/)}} // {{testaid4_eval}}
{{testaid5::exec(echo Carbon::parse('now');/*pad(54)*/)}} // {{testaid5_eval}}
{{hasTestNow::exec(var_dump(Carbon::hasTestNow());/*pad(54)*/)}} // {{hasTestNow_eval}}
{{::lint(Carbon::setTestNow();/*pad(54)*/)}} // clear the mock
{{hasTestNowNo::exec(var_dump(Carbon::hasTestNow());/*pad(54)*/)}} // {{hasTestNowNo_eval}}
{{backToNormal::exec(echo Carbon::now();/*pad(54)*/)}} // {{backToNormal_eval}}

A more meaning full example:

{{::lint(
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);
)}}
{{::lint(Carbon::setTestNow(Carbon::parse('first day of March 2000'));/*pad(40)*/)}}
{{product1::exec(echo $product->getPrice();/*pad(70)*/)}} // {{product1_eval}}
{{::lint(Carbon::setTestNow(Carbon::parse('first day of December 2000'));/*pad(40)*/)}}
{{product2::exec(echo $product->getPrice();/*pad(70)*/)}} // {{product2_eval}}
{{::lint(Carbon::setTestNow(Carbon::parse('first day of May 2000'));/*pad(40)*/)}}
{{product3::exec(echo $product->getPrice();/*pad(70)*/)}} // {{product3_eval}}
{{::lint(Carbon::setTestNow();)}}
### 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.

{{::lint($dt = Carbon::create(2012, 9, 5, 23, 26, 11);)}}

// These getters specifically return integers, ie intval()
{{getyear::exec(var_dump($dt->year);/*pad(54)*/)}} // {{getyear_eval}}
{{getmonth::exec(var_dump($dt->month);/*pad(54)*/)}} // {{getmonth_eval}}
{{getday::exec(var_dump($dt->day);/*pad(54)*/)}} // {{getday_eval}}
{{gethour::exec(var_dump($dt->hour);/*pad(54)*/)}} // {{gethour_eval}}
{{getminute::exec(var_dump($dt->minute);/*pad(54)*/)}} // {{getminute_eval}}
{{getsecond::exec(var_dump($dt->second);/*pad(54)*/)}} // {{getsecond_eval}}
{{getdow::exec(var_dump($dt->dayOfWeek);/*pad(54)*/)}} // {{getdow_eval}}
{{getdoy::exec(var_dump($dt->dayOfYear);/*pad(54)*/)}} // {{getdoy_eval}}
{{getwoy::exec(var_dump($dt->weekOfYear);/*pad(54)*/)}} // {{getwoy_eval}}
{{getdnm::exec(var_dump($dt->daysInMonth);/*pad(54)*/)}} // {{getdnm_eval}}
{{getts::exec(var_dump($dt->timestamp);/*pad(54)*/)}} // {{getts_eval}}
{{getage::exec(var_dump(Carbon::createFromDate(1975, 5, 21)->age);/*pad(54)*/)}} // {{getage_eval}} calculated vs now in the same tz
{{getq::exec(var_dump($dt->quarter);/*pad(54)*/)}} // {{getq_eval}}

// Returns an int of seconds difference from UTC (+/- sign included)
{{get1::exec(var_dump(Carbon::createFromTimestampUTC(0)->offset);/*pad(54)*/)}} // {{get1_eval}}
{{get2::exec(var_dump(Carbon::createFromTimestamp(0)->offset);/*pad(54)*/)}} // {{get2_eval}}

// Returns an int of hours difference from UTC (+/- sign included)
{{get3::exec(var_dump(Carbon::createFromTimestamp(0)->offsetHours);/*pad(54)*/)}} // {{get3_eval}}

// Indicates if day light savings time is on
{{get4::exec(var_dump(Carbon::createFromDate(2012, 1, 1)->dst);/*pad(54)*/)}} // {{get4_eval}}

// Gets the DateTimeZone instance
{{get5::exec(echo get_class(Carbon::now()->timezone);/*pad(54)*/)}} // {{get5_eval}}
{{get6::exec(echo get_class(Carbon::now()->tz);/*pad(54)*/)}} // {{get6_eval}}

// Gets the DateTimeZone instance name, shortcut for ->timezone->getName()
{{get7::exec(echo Carbon::now()->timezoneName;/*pad(54)*/)}} // {{get7_eval}}
{{get8::exec(echo Carbon::now()->tzName;/*pad(54)*/)}} // {{get8_eval}}
### 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.

{{::lint(
$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

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

No arguments are optional for the setters, but there are enough variety in the function definitions 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. Specifically, setting the timestamp will not set the corresponding timezone to UTC.

{{::lint(
$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) 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().

{{isset1::exec(var_dump(isset(Carbon::now()->iDoNotExist));/*pad(50)*/)}} // {{isset1_eval}}
{{isset2::exec(var_dump(isset(Carbon::now()->hour));/*pad(50)*/)}} // {{isset2_eval}}
{{isset3::exec(var_dump(empty(Carbon::now()->iDoNotExist));/*pad(50)*/)}} // {{isset3_eval}}
{{isset4::exec(var_dump(empty(Carbon::now()->year));/*pad(50)*/)}} // {{isset4_eval}}
### String Formatting and Localization

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.

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

{{format1::exec(var_dump($dt->toDateTimeString() == $dt);/*pad(50)*/)}} // {{format1_eval}} => uses __toString()
{{format2::exec(echo $dt->toDateString();/*pad(50)*/)}} // {{format2_eval}}
{{format3::exec(echo $dt->toFormattedDateString();/*pad(50)*/)}} // {{format3_eval}}
{{format4::exec(echo $dt->toTimeString();/*pad(50)*/)}} // {{format4_eval}}
{{format5::exec(echo $dt->toDateTimeString();/*pad(50)*/)}} // {{format5_eval}}
{{format6::exec(echo $dt->toDayDateTimeString();/*pad(50)*/)}} // {{format6_eval}}

// ... of course format() is still available
{{format7::exec(echo $dt->format('l jS \\of F Y h:i:s A');/*pad(50)*/)}} // {{format7_eval}}

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

{{::lint(setlocale(LC_TIME, 'German');/*pad(50)*/)}}
{{format20::exec(echo $dt->formatLocalized('%A %d %B %Y');/*pad(50)*/)}} // {{format20_eval}}
{{::lint(setlocale(LC_TIME, '');/*pad(50)*/)}}
{{format21::exec(echo $dt->formatLocalized('%A %d %B %Y');/*pad(50)*/)}} // {{format21_eval}}
## Common Formats

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

$dt = Carbon::now();

echo $dt->toATOMString();        // same as $dt->format(DateTime::ATOM);
echo $dt->toCOOKIEString();
echo $dt->toISO8601String();
echo $dt->toRFC822String();
echo $dt->toRFC850String();
echo $dt->toRFC1036String();
echo $dt->toRFC1123String();
echo $dt->toRFC2822String();
echo $dt->toRFC3339String();
echo $dt->toRSSString();
echo $dt->toW3CString();
### 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.

{{::lint($first = Carbon::create(2012, 9, 5, 23, 26, 11);)}}
{{::lint($second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');)}}

{{compare1::exec(echo $first->toDateTimeString();/*pad(50)*/)}} // {{compare1_eval}}
{{compare2::exec(echo $second->toDateTimeString();/*pad(50)*/)}} // {{compare2_eval}}

{{compare3::exec(var_dump($first->eq($second));/*pad(50)*/)}} // {{compare3_eval}}
{{compare4::exec(var_dump($first->ne($second));/*pad(50)*/)}} // {{compare4_eval}}
{{compare5::exec(var_dump($first->gt($second));/*pad(50)*/)}} // {{compare5_eval}}
{{compare6::exec(var_dump($first->gte($second));/*pad(50)*/)}} // {{compare6_eval}}
{{compare7::exec(var_dump($first->lt($second));/*pad(50)*/)}} // {{compare7_eval}}
{{compare8::exec(var_dump($first->lte($second));/*pad(50)*/)}} // {{compare8_eval}}

{{::lint($first->setDateTime(2012, 1, 1, 0, 0, 0);)}}
{{::lint($second->setDateTime(2012, 1, 1, 0, 0, 0);/*pad(50)*/)}} // Remember tz is 'America/Vancouver'

{{compare9::exec(var_dump($first->eq($second));/*pad(50)*/)}} // {{compare9_eval}}
{{compare10::exec(var_dump($first->ne($second));/*pad(50)*/)}} // {{compare10_eval}}
{{compare11::exec(var_dump($first->gt($second));/*pad(50)*/)}} // {{compare11_eval}}
{{compare12::exec(var_dump($first->gte($second));/*pad(50)*/)}} // {{compare12_eval}}
{{compare13::exec(var_dump($first->lt($second));/*pad(50)*/)}} // {{compare13_eval}}
{{compare14::exec(var_dump($first->lte($second));/*pad(50)*/)}} // {{compare14_eval}}

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.

{{::lint($first = Carbon::create(2012, 9, 5, 1);)}}
{{::lint($second = Carbon::create(2012, 9, 5, 5);)}}
{{between1::exec(var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second));/*pad(75)*/)}} // {{between1_eval}}
{{between2::exec(var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second));/*pad(75)*/)}} // {{between2_eval}}
{{between3::exec(var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false));/*pad(75)*/)}} // {{between3_eval}}

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.

{{::lint(
$dt = Carbon::now();

$dt->isWeekday();
$dt->isWeekend();
$dt->isYesterday();
$dt->isToday();
$dt->isTomorrow();
$dt->isFuture();
$dt->isPast();
$dt->isLeapYear();
)}}
### Addition and Subtraction

The default DateTime provides a couple of different methods for easily adding and subtracting time. There is modify(), add() and sub(). modify() takes a magical date/time format string, 'last day of next month', that it parses and applies the modification while add() and sub() use a DateInterval class thats not so obvious, new \DateInterval('P6YT5M'). 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.

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

{{addsub1::exec(echo $dt->toDateTimeString();/*pad(40)*/)}} // {{addsub1_eval}}

{{addsub2::exec(echo $dt->addYears(5);/*pad(40)*/)}} // {{addsub2_eval}}
{{addsub3::exec(echo $dt->addYear();/*pad(40)*/)}} // {{addsub3_eval}}
{{addsub4::exec(echo $dt->subYear();/*pad(40)*/)}} // {{addsub4_eval}}
{{addsub5::exec(echo $dt->subYears(5);/*pad(40)*/)}} // {{addsub5_eval}}

{{addsub6::exec(echo $dt->addMonths(60);/*pad(40)*/)}} // {{addsub6_eval}}
{{addsub7::exec(echo $dt->addMonth();/*pad(40)*/)}} // {{addsub7_eval}} equivalent of $dt->month($dt->month + 1); so it wraps
{{addsub8::exec(echo $dt->subMonth();/*pad(40)*/)}} // {{addsub8_eval}}
{{addsub9::exec(echo $dt->subMonths(60);/*pad(40)*/)}} // {{addsub9_eval}}

{{addsub10::exec(echo $dt->addDays(29);/*pad(40)*/)}} // {{addsub10_eval}}
{{addsub11::exec(echo $dt->addDay();/*pad(40)*/)}} // {{addsub11_eval}}
{{addsub12::exec(echo $dt->subDay();/*pad(40)*/)}} // {{addsub12_eval}}
{{addsub13::exec(echo $dt->subDays(29);/*pad(40)*/)}} // {{addsub13_eval}}

{{addsub14::exec(echo $dt->addWeekdays(4);/*pad(40)*/)}} // {{addsub14_eval}}
{{addsub15::exec(echo $dt->addWeekday();/*pad(40)*/)}} // {{addsub15_eval}}
{{addsub16::exec(echo $dt->subWeekday();/*pad(40)*/)}} // {{addsub16_eval}}
{{addsub17::exec(echo $dt->subWeekdays(4);/*pad(40)*/)}} // {{addsub17_eval}}

{{addsub18::exec(echo $dt->addWeeks(3);/*pad(40)*/)}} // {{addsub18_eval}}
{{addsub19::exec(echo $dt->addWeek();/*pad(40)*/)}} // {{addsub19_eval}}
{{addsub20::exec(echo $dt->subWeek();/*pad(40)*/)}} // {{addsub20_eval}}
{{addsub21::exec(echo $dt->subWeeks(3);/*pad(40)*/)}} // {{addsub21_eval}}

{{addsub22::exec(echo $dt->addHours(24);/*pad(40)*/)}} // {{addsub22_eval}}
{{addsub23::exec(echo $dt->addHour();/*pad(40)*/)}} // {{addsub23_eval}}
{{addsub24::exec(echo $dt->subHour();/*pad(40)*/)}} // {{addsub24_eval}}
{{addsub25::exec(echo $dt->subHours(24);/*pad(40)*/)}} // {{addsub25_eval}}

{{addsub26::exec(echo $dt->addMinutes(61);/*pad(40)*/)}} // {{addsub26_eval}}
{{addsub27::exec(echo $dt->addMinute();/*pad(40)*/)}} // {{addsub27_eval}}
{{addsub28::exec(echo $dt->subMinute();/*pad(40)*/)}} // {{addsub28_eval}}
{{addsub29::exec(echo $dt->subMinutes(61);/*pad(40)*/)}} // {{addsub29_eval}}

{{addsub30::exec(echo $dt->addSeconds(61);/*pad(40)*/)}} // {{addsub30_eval}}
{{addsub31::exec(echo $dt->addSecond();/*pad(40)*/)}} // {{addsub31_eval}}
{{addsub32::exec(echo $dt->subSecond();/*pad(40)*/)}} // {{addsub32_eval}}
{{addsub33::exec(echo $dt->subSeconds(61);/*pad(40)*/)}} // {{addsub33_eval}}

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

### Difference

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 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 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. The comparisons are done in UTC.

// Carbon::diffInYears(Carbon $dt = null, $abs = true)

{{diff1::exec(echo Carbon::now('America/Vancouver')->diffInSeconds(Carbon::now('Europe/London'));)}} // {{diff1_eval}}

{{::lint($dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');)}}
{{::lint($dtVancouver = Carbon::createFromDate(2000, 1, 1, 'America/Vancouver');)}}
{{diff4::exec(echo $dtOttawa->diffInHours($dtVancouver);/*pad(70)*/)}} // {{diff4_eval}}

{{diff5::exec(echo $dtOttawa->diffInHours($dtVancouver, false);/*pad(70)*/)}} // {{diff5_eval}}
{{diff6::exec(echo $dtVancouver->diffInHours($dtOttawa, false);/*pad(70)*/)}} // {{diff6_eval}}

{{::lint($dt = Carbon::create(2012, 1, 31, 0);)}}
{{diff8::exec(echo $dt->diffInDays($dt->copy()->addMonth());/*pad(70)*/)}} // {{diff8_eval}}
{{diff9::exec(echo $dt->diffInDays($dt->copy()->subMonth(), false);/*pad(70)*/)}} // {{diff9_eval}}

{{::lint($dt = Carbon::create(2012, 4, 30, 0);)}}
{{diff11::exec(echo $dt->diffInDays($dt->copy()->addMonth());/*pad(70)*/)}} // {{diff11_eval}}
{{diff12::exec(echo $dt->diffInDays($dt->copy()->addWeek());/*pad(70)*/)}} // {{diff12_eval}}

{{::lint($dt = Carbon::create(2012, 1, 1, 0);)}}
{{diff14::exec(echo $dt->diffInMinutes($dt->copy()->addSeconds(59));/*pad(70)*/)}} // {{diff14_eval}}
{{diff15::exec(echo $dt->diffInMinutes($dt->copy()->addSeconds(60));/*pad(70)*/)}} // {{diff15_eval}}
{{diff16::exec(echo $dt->diffInMinutes($dt->copy()->addSeconds(119));/*pad(70)*/)}} // {{diff16_eval}}
{{diff17::exec(echo $dt->diffInMinutes($dt->copy()->addSeconds(120));/*pad(70)*/)}} // {{diff17_eval}}

// others that are defined
// diffInYears(), diffInMonths(), diffInDays()
// diffInHours(), diffInMinutes(), diffInSeconds()
### 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. It uses approximations for month being 30 days which then equates a year to 360 days. 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
// The most typical usage is for comments
// The instance is the date the comment was created and its being compared to default now()
{{humandiff1::exec(echo Carbon::now()->subDays(5)->diffForHumans();/*pad(62)*/)}} // {{humandiff1_eval}}

{{humandiff2::exec(echo Carbon::now()->diffForHumans(Carbon::now()->subYear());/*pad(62)*/)}} // {{humandiff2_eval}}

{{::lint($dt = Carbon::createFromDate(2011, 2, 1);)}}

{{humandiff4::exec(echo $dt->diffForHumans($dt->copy()->addMonth());/*pad(62)*/)}} // {{humandiff4_eval}}
{{humandiff5::exec(echo $dt->diffForHumans($dt->copy()->subMonth());/*pad(62)*/)}} // {{humandiff5_eval}}

{{humandiff6::exec(echo Carbon::now()->addSeconds(5)->diffForHumans();/*pad(62)*/)}} // {{humandiff6_eval}}
### 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() methods set the time to 00:00:00 and the endOfXXX() methods set the time to 23:59:59.

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);/*pad(40)*/)}}
{{modifier1::exec(echo $dt->startOfDay();/*pad(50)*/)}} // {{modifier1_eval}}

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier2::exec(echo $dt->endOfDay();/*pad(50)*/)}} // {{modifier2_eval}}

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier3::exec(echo $dt->startOfMonth();/*pad(50)*/)}} // {{modifier3_eval}}

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier4::exec(echo $dt->endOfMonth();/*pad(50)*/)}} // {{modifier4_eval}}

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier5::exec(echo $dt->startOfWeek();/*pad(50)*/)}} // {{modifier5_eval}}
{{modifier6::exec(var_dump($dt->dayOfWeek == Carbon::MONDAY);/*pad(50)*/)}} // {{modifier6_eval}} : ISO8601 week starts on Monday

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier7::exec(echo $dt->endOfWeek();/*pad(50)*/)}} // {{modifier7_eval}}
{{modifier8::exec(var_dump($dt->dayOfWeek == Carbon::SUNDAY);/*pad(50)*/)}} // {{modifier8_eval}} : ISO8601 week ends on Sunday

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier9::exec(echo $dt->next(Carbon::WEDNESDAY);/*pad(50)*/)}} // {{modifier9_eval}}
{{modifier10::exec(var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);/*pad(50)*/)}} // {{modifier10_eval}}

{{::lint($dt = Carbon::create(2012, 1, 1, 12, 0, 0);)}}
{{modifier11::exec(echo $dt->next();/*pad(50)*/)}} // {{modifier11_eval}}

{{::lint($dt = Carbon::create(2012, 1, 31, 12, 0, 0);)}}
{{modifier12::exec(echo $dt->previous(Carbon::WEDNESDAY);/*pad(50)*/)}} // {{modifier12_eval}}
{{modifier13::exec(var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);/*pad(50)*/)}} // {{modifier13_eval}}

{{::lint($dt = Carbon::create(2012, 1, 1, 12, 0, 0);)}}
{{modifier14::exec(echo $dt->previous();/*pad(50)*/)}} // {{modifier14_eval}}

// others that are defined that are similar
//   firstOfMonth(), lastOfMonth(), nthOfMonth()
//   firstOfQuarter(), lastOfQuarter(), nthOfQuarter()
//   firstOfYear(), lastOfYear(), nthOfYear()
### Constants

The following constants are defined in the Carbon class.

  • SUNDAY = 0
  • MONDAY = 1
  • TUESDAY = 2
  • WEDNESDAY = 3
  • THURSDAY = 4
  • FRIDAY = 5
  • SATURDAY = 6
  • MONTHS_PER_YEAR = 12
  • HOURS_PER_DAY = 24
  • MINUTES_PER_HOUR = 60
  • SECONDS_PER_MINUTE = 60
{{::lint(
$dt = Carbon::createFromDate(2012, 10, 6);
if ($dt->dayOfWeek === Carbon::SATURDAY) {
    echo 'Place bets on Ottawa Senators Winning!';
}
)}}
## About ### Contributing

I hate reading a readme.md file that has code errors and/or sample output that is incorrect. I tried something new with this project and wrote a quick readme parser that can lint sample source code or execute and inject the actual result into a generated readme.

Don't make changes to the readme.md directly!!

Change the readme.src.md and then use the readme.php to generate the new readme.md file. It can be run at the command line using php readme.php from the project root. Maybe someday I'll extract this out to another project or at least run it with a post receive hook, but for now its just a local tool, deal with it.

The commands are quickly explained below. To see some examples you can view the raw readme.src.md file in this repo.

\{\{::lint()}}

The lint command is meant for confirming the code is valid and will eval() the code passed into the function. Assuming there were no errors, the executed source code will then be injected back into the text replacing out the \{\{::lint()}}. When you look at the raw readme.src.md you will see that the code can span several lines. Remember the code is executed in the context of the running script so any variables will be available for the rest of the file.

\{\{::lint($var = 'brian nesbitt';)}} => {{::lint($var = 'brian nesbitt';)}}

As mentioned the $var can later be echo'd and you would get 'brian nesbitt' as all of the source is executed in the same scope.

\{\{varName::exec()}} and {{varName_eval}}

The exec command begins by performing an eval() on the code passed into the function. The executed source code will then be injected back into the text replacing out the \{\{varName::exec()}}. This will also create a variable named varName_eval that you can then place anywhere in the file and it will get replaced with the output of the eval(). You can use any type of output (echo, printf, var_dump etc) statement to return the result value as an output buffer is setup to capture the output.

\{\{exVarName::exec(echo $var;)}} => {{exVarName::exec(echo $var;)}}
\{\{exVarName_eval}} => {{exVarName_eval}}  // $var is still set from above

/*pad()*/

The pad() is a special source modifier. This will pad the code block to the indicated number of characters using spaces. Its particularly handy for aligning // comments when showing results.

\{\{exVarName1::exec(echo 12345;/*pad(20)*/)}} // \{\{exVarName1_eval}}
\{\{exVarName2::exec(echo 6;/*pad(20)*/)}} // \{\{exVarName2_eval}}

... would generate to:

{{exVarName1::exec(echo 12345;/*pad(20)*/)}} // {{exVarName1_eval}}
{{exVarName2::exec(echo 6;/*pad(20)*/)}} // {{exVarName2_eval}}

Apart from the readme the typical steps can be used to contribute your own improvements.

  • Fork
  • Clone
  • PHPUnit
  • Branch
  • PHPUnit
  • Code
  • PHPUnit
  • Commit
  • Push
  • Pull request
  • Relax and play Castle Crashers
### Author

Brian Nesbitt - brian@nesbot.com - http://twitter.com/NesbittBrian

### License

Carbon is licensed under the MIT License - see the LICENSE file for details

### History

You can view the history of the Carbon project in the history file.

### Why the name Carbon?

Read about Carbon Dating