PageRenderTime 75ms CodeModel.GetById 2ms app.highlight 66ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/nesbot/carbon/readme.md

https://gitlab.com/vineethkrishnan/Laravel-Eloquent-Relationship-Example
Markdown | 865 lines | 641 code | 224 blank | 0 comment | 0 complexity | 8ec7d9bd69bad989ddbd2ef7819a6fa9 MD5 | raw file
  1> **This file is autogenerated.  Please see the [Contributing](#about-contributing) section from more information.**
  2
  3# Carbon
  4
  5[![Latest Stable Version](https://poser.pugx.org/nesbot/carbon/v/stable.png)](https://packagist.org/packages/nesbot/carbon) [![Total Downloads](https://poser.pugx.org/nesbot/carbon/downloads.png)](https://packagist.org/packages/nesbot/carbon) [![Build Status](https://secure.travis-ci.org/briannesbitt/Carbon.png)](http://travis-ci.org/briannesbitt/Carbon)
  6
  7A simple API extension for DateTime with PHP 5.3+
  8
  9```php
 10printf("Right now is %s", Carbon::now()->toDateTimeString());
 11printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver'));  //implicit __toString()
 12$tomorrow = Carbon::now()->addDay();
 13$lastWeek = Carbon::now()->subWeek();
 14$nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);
 15
 16$officialDate = Carbon::now()->toRFC2822String();
 17
 18$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
 19
 20$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
 21
 22$worldWillEnd = Carbon::createFromDate(2012, 12, 21, 'GMT');
 23
 24// Don't really want to die so mock now
 25Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
 26
 27// comparisons are always done in UTC
 28if (Carbon::now()->gte($worldWillEnd)) {
 29   die();
 30}
 31
 32// Phew! Return to normal behaviour
 33Carbon::setTestNow();
 34
 35if (Carbon::now()->isWeekend()) {
 36   echo 'Party!';
 37}
 38echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
 39
 40// ... but also does 'from now', 'after' and 'before'
 41// rolling up to seconds, minutes, hours, days, months, years
 42
 43$daysSinceEpoch = Carbon::createFromTimeStamp(0)->diffInDays();
 44```
 45
 46## README Contents
 47
 48* [Installation](#install)
 49    * [Requirements](#requirements)
 50    * [With composer](#install-composer)
 51    * [Without composer](#install-nocomposer)
 52* [API](#api)
 53    * [Instantiation](#api-instantiation)
 54    * [Testing Aids](#api-testing)
 55    * [Getters](#api-getters)
 56    * [Setters](#api-setters)
 57    * [Fluent Setters](#api-settersfluent)
 58    * [IsSet](#api-isset)
 59    * [String Formatting and Localization](#api-formatting)
 60    * [Common Formats](#api-commonformats)
 61    * [Comparison](#api-comparison)
 62    * [Addition and Subtraction](#api-addsub)
 63    * [Difference](#api-difference)
 64    * [Difference for Humans](#api-humandiff)
 65    * [Modifiers](#api-modifiers)
 66    * [Constants](#api-constants)
 67* [About](#about)
 68    * [Contributing](#about-contributing)
 69    * [Author](#about-author)
 70    * [License](#about-license)
 71    * [History](#about-history)
 72    * [Why the name Carbon?](#about-whyname)
 73
 74<a name="install"/>
 75## Installation
 76
 77<a name="requirements"/>
 78### Requirements
 79
 80- Any flavour of PHP 5.3+ should do
 81- [optional] PHPUnit to execute the test suite
 82
 83<a name="install-composer"/>
 84### With Composer
 85
 86The easiest way to install Carbon is via [composer](http://getcomposer.org/). Create the following `composer.json` file and run the `php composer.phar install` command to install it.
 87
 88```json
 89{
 90    "require": {
 91        "nesbot/Carbon": "*"
 92    }
 93}
 94```
 95
 96```php
 97<?php
 98require 'vendor/autoload.php';
 99
100use Carbon\Carbon;
101
102printf("Now: %s", Carbon::now());
103```
104
105<a name="install-nocomposer"/>
106### Without Composer
107
108Why are you not using [composer](http://getcomposer.org/)? Download [Carbon.php](https://github.com/briannesbitt/Carbon/blob/master/Carbon/Carbon.php) from the repo and save the file into your project path somewhere.
109
110```php
111<?php
112require 'path/to/Carbon.php';
113
114use Carbon\Carbon;
115
116printf("Now: %s", Carbon::now());
117```
118
119<a name="api"/>
120## API
121
122The Carbon class is [inherited](http://php.net/manual/en/keyword.extends.php) from the PHP [DateTime](http://www.php.net/manual/en/class.datetime.php) class.
123
124```php
125<?php
126class Carbon extends \DateTime
127{
128    // code here
129}
130```
131
132Carbon 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.
133
134> **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.**
135
136Special 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.
137
138```php
139$dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto');
140$dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver');
141
142echo $dtVancouver->diffInHours($dtToronto); // 3
143```
144
145Also `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.
146
147<a name="api-instantiation"/>
148### Instantiation
149
150There are several different 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 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.
151
152```php
153$carbon = new Carbon();                  // equivalent to Carbon::now()
154$carbon = new Carbon('first day of January 2008', 'America/Vancouver');
155echo get_class($carbon);                 // 'Carbon\Carbon'
156```
157
158You'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.
159
160```php
161$now = Carbon::now();
162
163$nowInLondonTz = Carbon::now(new DateTimeZone('Europe/London'));
164
165// or just pass the timezone as a string
166$nowInLondonTz = Carbon::now('Europe/London');
167```
168
169If 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.
170
171```php
172echo (new Carbon('first day of December 2008'))->addWeeks(2);     // 2008-12-15 00:00:00
173echo Carbon::parse('first day of December 2008')->addWeeks(2);    // 2008-12-15 00:00:00
174```
175
176To 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`.
177
178```php
179$now = Carbon::now();
180echo $now;                               // 2014-01-06 22:52:03
181$today = Carbon::today();
182echo $today;                             // 2014-01-06 00:00:00
183$tomorrow = Carbon::tomorrow('Europe/London');
184echo $tomorrow;                          // 2014-01-08 00:00:00
185$yesterday = Carbon::yesterday();
186echo $yesterday;                         // 2014-01-05 00:00:00
187```
188
189The 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.
190
191```php
192Carbon::createFromDate($year, $month, $day, $tz);
193Carbon::createFromTime($hour, $minute, $second, $tz);
194Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
195```
196
197`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.
198
199```php
200$xmasThisYear = Carbon::createFromDate(null, 12, 25);  // Year defaults to current year
201$Y2K = Carbon::create(2000, 1, 1, 0, 0, 0);
202$alsoY2K = Carbon::create(1999, 12, 31, 24);
203$noonLondonTz = Carbon::createFromTime(12, 0, 0, 'Europe/London');
204
205// A two digit minute could not be found
206try { Carbon::create(1975, 5, 21, 22, -2, 0); } catch(InvalidArgumentException $x) { echo $x->getMessage(); }
207```
208
209```php
210Carbon::createFromFormat($format, $time, $tz);
211```
212
213`createFromFormat()` is mostly a wrapper for the base php function [DateTime::createFromFormat](http://php.net/manual/en/datetime.createfromformat.php).  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()`.
214
215```php
216echo Carbon::createFromFormat('Y-m-d H', '1975-05-21 22')->toDateTimeString(); // 1975-05-21 22:00:00
217```
218
219The final two create functions are for working with [unix timestamps](http://en.wikipedia.org/wiki/Unix_time).  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.
220
221```php
222echo Carbon::createFromTimeStamp(-1)->toDateTimeString();                        // 1969-12-31 18:59:59
223echo Carbon::createFromTimeStamp(-1, 'Europe/London')->toDateTimeString();       // 1970-01-01 00:59:59
224echo Carbon::createFromTimeStampUTC(-1)->toDateTimeString();                     // 1969-12-31 23:59:59
225```
226
227You 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.
228
229```php
230$dt = Carbon::now();
231echo $dt->diffInYears($dt->copy()->addYear());  // 1
232
233// $dt was unchanged and still holds the value of Carbon:now()
234```
235
236Finally, if you find yourself inheriting a `\DateTime` instance from another library, fear not!  You can create a `Carbon` instance via a friendly `instance()` function.
237
238```php
239$dt = new \DateTime('first day of January 2008'); // <== instance from another API
240$carbon = Carbon::instance($dt);
241echo get_class($carbon);                               // 'Carbon\Carbon'
242echo $carbon->toDateTimeString();                      // 2008-01-01 00:00:00
243```
244
245<a name="api-testing"/>
246### Testing Aids
247
248The 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:
249- A call to the static now() method, ex. Carbon::now()
250- When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null)
251- When the string "now" is passed to the constructor or parse(), ex. new Carbon('now')
252
253```php
254$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
255Carbon::setTestNow($knownDate);                        // set the mock (of course this could be a real mock object)
256echo Carbon::now();                                    // 2001-05-21 12:00:00
257echo new Carbon();                                     // 2001-05-21 12:00:00
258echo Carbon::parse();                                  // 2001-05-21 12:00:00
259echo new Carbon('now');                                // 2001-05-21 12:00:00
260echo Carbon::parse('now');                             // 2001-05-21 12:00:00
261var_dump(Carbon::hasTestNow());                        // bool(true)
262Carbon::setTestNow();                                  // clear the mock
263var_dump(Carbon::hasTestNow());                        // bool(false)
264echo Carbon::now();                                    // 2014-01-06 22:52:03
265```
266
267A more meaning full example:
268
269```php
270class SeasonalProduct
271{
272    protected $price;
273
274    public function __construct($price)
275    {
276        $this->price = $price;
277    }
278
279    public function getPrice() {
280        $multiplier = 1;
281        if (Carbon::now()->month == 12) {
282            $multiplier = 2;
283        }
284
285        return $this->price * $multiplier;
286    }
287}
288
289$product = new SeasonalProduct(100);
290Carbon::setTestNow(Carbon::parse('first day of March 2000'));
291echo $product->getPrice();                                             // 100
292Carbon::setTestNow(Carbon::parse('first day of December 2000'));
293echo $product->getPrice();                                             // 200
294Carbon::setTestNow(Carbon::parse('first day of May 2000'));
295echo $product->getPrice();                                             // 100
296Carbon::setTestNow();
297```
298
299Relative phrases are also mocked according to the given "now" instance.
300
301```php
302$knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
303Carbon::setTestNow($knownDate);                        // set the mock
304echo new Carbon('tomorrow');                           // 2001-05-22 00:00:00
305echo new Carbon('yesterday');                          // 2001-05-20 00:00:00
306echo new Carbon('next wednesday');                     // 2001-05-23 00:00:00
307echo new Carbon('last friday');                        // 2001-05-18 00:00:00
308echo new Carbon('this thursday');                      // 2001-05-24 00:00:00
309Carbon::setTestNow();                                  // always clear it !
310```
311
312The list of words that are considered to be relative modifiers are:
313- this
314- next
315- last
316- tomorrow
317- yesterday
318- +
319- -
320- first
321- last
322- ago
323
324Be aware that similar to the next(), previous() and modify() methods some of these relative modifiers will set the time to 00:00:00.
325
326<a name="api-getters"/>
327### Getters
328
329The 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.
330
331```php
332$dt = Carbon::create(2012, 9, 5, 23, 26, 11);
333
334// These getters specifically return integers, ie intval()
335var_dump($dt->year);                                         // int(2012)
336var_dump($dt->month);                                        // int(9)
337var_dump($dt->day);                                          // int(5)
338var_dump($dt->hour);                                         // int(23)
339var_dump($dt->minute);                                       // int(26)
340var_dump($dt->second);                                       // int(11)
341var_dump($dt->dayOfWeek);                                    // int(3)
342var_dump($dt->dayOfYear);                                    // int(248)
343var_dump($dt->weekOfYear);                                   // int(36)
344var_dump($dt->daysInMonth);                                  // int(30)
345var_dump($dt->timestamp);                                    // int(1346901971)
346var_dump(Carbon::createFromDate(1975, 5, 21)->age);          // int(38) calculated vs now in the same tz
347var_dump($dt->quarter);                                      // int(3)
348
349// Returns an int of seconds difference from UTC (+/- sign included)
350var_dump(Carbon::createFromTimestampUTC(0)->offset);         // int(0)
351var_dump(Carbon::createFromTimestamp(0)->offset);            // int(-18000)
352
353// Returns an int of hours difference from UTC (+/- sign included)
354var_dump(Carbon::createFromTimestamp(0)->offsetHours);       // int(-5)
355
356// Indicates if day light savings time is on
357var_dump(Carbon::createFromDate(2012, 1, 1)->dst);           // bool(false)
358var_dump(Carbon::createFromDate(2012, 9, 1)->dst);           // bool(true)
359
360// Indicates if the instance is in the same timezone as the local timzezone
361var_dump(Carbon::now()->local);                              // bool(true)
362var_dump(Carbon::now('America/Vancouver')->local);           // bool(false)
363
364// Indicates if the instance is in the UTC timezone
365var_dump(Carbon::now()->utc);                                // bool(false)
366var_dump(Carbon::now('Europe/London')->utc);                 // bool(true)
367var_dump(Carbon::createFromTimestampUTC(0)->utc);            // bool(true)
368
369// Gets the DateTimeZone instance
370echo get_class(Carbon::now()->timezone);                     // DateTimeZone
371echo get_class(Carbon::now()->tz);                           // DateTimeZone
372
373// Gets the DateTimeZone instance name, shortcut for ->timezone->getName()
374echo Carbon::now()->timezoneName;                            // America/Toronto
375echo Carbon::now()->tzName;                                  // America/Toronto
376```
377
378<a name="api-setters"/>
379### Setters
380
381The 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.
382
383```php
384$dt = Carbon::now();
385
386$dt->year = 1975;
387$dt->month = 13;             // would force year++ and month = 1
388$dt->month = 5;
389$dt->day = 21;
390$dt->hour = 22;
391$dt->minute = 32;
392$dt->second = 5;
393
394$dt->timestamp = 169957925;  // This will not change the timezone
395
396// Set the timezone via DateTimeZone instance or string
397$dt->timezone = new DateTimeZone('Europe/London');
398$dt->timezone = 'Europe/London';
399$dt->tz = 'Europe/London';
400```
401
402<a name="api-settersfluent"/>
403### Fluent Setters
404
405No 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.
406
407```php
408$dt = Carbon::now();
409
410$dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString();
411$dt->setDate(1975, 5, 21)->setTime(22, 32, 5)->toDateTimeString();
412$dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();
413
414$dt->timestamp(169957925)->timezone('Europe/London');
415
416$dt->tz('America/Toronto')->setTimezone('America/Vancouver');
417```
418
419<a name="api-isset"/>
420### IsSet
421
422The 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).
423
424```php
425var_dump(isset(Carbon::now()->iDoNotExist));       // bool(false)
426var_dump(isset(Carbon::now()->hour));              // bool(true)
427var_dump(empty(Carbon::now()->iDoNotExist));       // bool(true)
428var_dump(empty(Carbon::now()->year));              // bool(false)
429```
430
431<a name="api-formatting"/>
432### String Formatting and Localization
433
434All 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 defined which allows a Carbon instance to be printed as a pretty date time string when used in a string context.
435
436```php
437$dt = Carbon::create(1975, 12, 25, 14, 15, 16);
438
439var_dump($dt->toDateTimeString() == $dt);          // bool(true) => uses __toString()
440echo $dt->toDateString();                          // 1975-12-25
441echo $dt->toFormattedDateString();                 // Dec 25, 1975
442echo $dt->toTimeString();                          // 14:15:16
443echo $dt->toDateTimeString();                      // 1975-12-25 14:15:16
444echo $dt->toDayDateTimeString();                   // Thu, Dec 25, 1975 2:15 PM
445
446// ... of course format() is still available
447echo $dt->format('l jS \\of F Y h:i:s A');         // Thursday 25th of December 1975 02:15:16 PM
448```
449
450You 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.
451
452```php
453Carbon::setToStringFormat('jS \o\f F, Y g:i:s a');
454echo $dt;                                          // 25th of December, 1975 2:15:16 pm
455Carbon::resetToStringFormat();
456echo $dt;                                          // 1975-12-25 14:15:16
457```
458
459Unfortunately 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](http://www.php.net/strftime) using the current instance timestamp.  If you first set the current locale with [setlocale()](http://www.php.net/setlocale) then the string returned will be formatted in the correct locale.
460
461```php
462setlocale(LC_TIME, 'German');                     
463echo $dt->formatLocalized('%A %d %B %Y');          // Donnerstag 25 Dezember 1975
464setlocale(LC_TIME, '');                           
465echo $dt->formatLocalized('%A %d %B %Y');          // Thursday 25 December 1975
466```
467
468<a name="api-commonformats"/>
469## Common Formats
470
471The following are wrappers for the common formats provided in the [DateTime class](http://www.php.net/manual/en/class.datetime.php).
472
473```php
474$dt = Carbon::now();
475
476echo $dt->toATOMString();        // same as $dt->format(DateTime::ATOM);
477echo $dt->toCOOKIEString();
478echo $dt->toISO8601String();
479echo $dt->toRFC822String();
480echo $dt->toRFC850String();
481echo $dt->toRFC1036String();
482echo $dt->toRFC1123String();
483echo $dt->toRFC2822String();
484echo $dt->toRFC3339String();
485echo $dt->toRSSString();
486echo $dt->toW3CString();
487```
488
489<a name="api-comparison"/>
490### Comparison
491
492Simple 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.
493
494```php
495echo Carbon::now()->tzName;                        // America/Toronto
496$first = Carbon::create(2012, 9, 5, 23, 26, 11);
497$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');
498
499echo $first->toDateTimeString();                   // 2012-09-05 23:26:11
500echo $first->tzName;                               // America/Toronto
501echo $second->toDateTimeString();                  // 2012-09-05 20:26:11
502echo $second->tzName;                              // America/Vancouver
503
504var_dump($first->eq($second));                     // bool(true)
505var_dump($first->ne($second));                     // bool(false)
506var_dump($first->gt($second));                     // bool(false)
507var_dump($first->gte($second));                    // bool(true)
508var_dump($first->lt($second));                     // bool(false)
509var_dump($first->lte($second));                    // bool(true)
510
511$first->setDateTime(2012, 1, 1, 0, 0, 0);
512$second->setDateTime(2012, 1, 1, 0, 0, 0);         // Remember tz is 'America/Vancouver'
513
514var_dump($first->eq($second));                     // bool(false)
515var_dump($first->ne($second));                     // bool(true)
516var_dump($first->gt($second));                     // bool(false)
517var_dump($first->gte($second));                    // bool(false)
518var_dump($first->lt($second));                     // bool(true)
519var_dump($first->lte($second));                    // bool(true)
520```
521
522To 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.
523
524```php
525$first = Carbon::create(2012, 9, 5, 1);
526$second = Carbon::create(2012, 9, 5, 5);
527var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second));          // bool(true)
528var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second));          // bool(true)
529var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false));   // bool(false)
530```
531
532Woah! 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 specified.
533
534```php
535$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
536$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
537echo $dt1->min($dt2);                              // 2012-01-01 00:00:00
538
539$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
540$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
541echo $dt1->max($dt2);                              // 2014-01-30 00:00:00
542
543// now is the default param
544$dt1 = Carbon::create(2000, 1, 1, 0, 0, 0);
545echo $dt1->max();                                  // 2014-01-06 22:52:03
546```
547
548To 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.
549
550```php
551$dt = Carbon::now();
552
553$dt->isWeekday();
554$dt->isWeekend();
555$dt->isYesterday();
556$dt->isToday();
557$dt->isTomorrow();
558$dt->isFuture();
559$dt->isPast();
560$dt->isLeapYear();
561```
562
563<a name="api-addsub"/>
564### Addition and Subtraction
565
566The 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.
567
568```php
569$dt = Carbon::create(2012, 1, 31, 0);
570
571echo $dt->toDateTimeString();            // 2012-01-31 00:00:00
572
573echo $dt->addYears(5);                   // 2017-01-31 00:00:00
574echo $dt->addYear();                     // 2018-01-31 00:00:00
575echo $dt->subYear();                     // 2017-01-31 00:00:00
576echo $dt->subYears(5);                   // 2012-01-31 00:00:00
577
578echo $dt->addMonths(60);                 // 2017-01-31 00:00:00
579echo $dt->addMonth();                    // 2017-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps
580echo $dt->subMonth();                    // 2017-02-03 00:00:00
581echo $dt->subMonths(60);                 // 2012-02-03 00:00:00
582
583echo $dt->addDays(29);                   // 2012-03-03 00:00:00
584echo $dt->addDay();                      // 2012-03-04 00:00:00
585echo $dt->subDay();                      // 2012-03-03 00:00:00
586echo $dt->subDays(29);                   // 2012-02-03 00:00:00
587
588echo $dt->addWeekdays(4);                // 2012-02-09 00:00:00
589echo $dt->addWeekday();                  // 2012-02-10 00:00:00
590echo $dt->subWeekday();                  // 2012-02-09 00:00:00
591echo $dt->subWeekdays(4);                // 2012-02-03 00:00:00
592
593echo $dt->addWeeks(3);                   // 2012-02-24 00:00:00
594echo $dt->addWeek();                     // 2012-03-02 00:00:00
595echo $dt->subWeek();                     // 2012-02-24 00:00:00
596echo $dt->subWeeks(3);                   // 2012-02-03 00:00:00
597
598echo $dt->addHours(24);                  // 2012-02-04 00:00:00
599echo $dt->addHour();                     // 2012-02-04 01:00:00
600echo $dt->subHour();                     // 2012-02-04 00:00:00
601echo $dt->subHours(24);                  // 2012-02-03 00:00:00
602
603echo $dt->addMinutes(61);                // 2012-02-03 01:01:00
604echo $dt->addMinute();                   // 2012-02-03 01:02:00
605echo $dt->subMinute();                   // 2012-02-03 01:01:00
606echo $dt->subMinutes(61);                // 2012-02-03 00:00:00
607
608echo $dt->addSeconds(61);                // 2012-02-03 00:01:01
609echo $dt->addSecond();                   // 2012-02-03 00:01:02
610echo $dt->subSecond();                   // 2012-02-03 00:01:01
611echo $dt->subSeconds(61);                // 2012-02-03 00:00:00
612```
613
614For fun you can also pass negative values to `addXXX()`, in fact that's how `subXXX()` is implemented.
615
616<a name="api-difference"/>
617### Difference
618
619These 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.
620
621```php
622// Carbon::diffInYears(Carbon $dt = null, $abs = true)
623
624echo Carbon::now('America/Vancouver')->diffInSeconds(Carbon::now('Europe/London')); // 0
625
626$dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
627$dtVancouver = Carbon::createFromDate(2000, 1, 1, 'America/Vancouver');
628echo $dtOttawa->diffInHours($dtVancouver);                             // 3
629
630echo $dtOttawa->diffInHours($dtVancouver, false);                      // 3
631echo $dtVancouver->diffInHours($dtOttawa, false);                      // -3
632
633$dt = Carbon::create(2012, 1, 31, 0);
634echo $dt->diffInDays($dt->copy()->addMonth());                         // 31
635echo $dt->diffInDays($dt->copy()->subMonth(), false);                  // -31
636
637$dt = Carbon::create(2012, 4, 30, 0);
638echo $dt->diffInDays($dt->copy()->addMonth());                         // 30
639echo $dt->diffInDays($dt->copy()->addWeek());                          // 7
640
641$dt = Carbon::create(2012, 1, 1, 0);
642echo $dt->diffInMinutes($dt->copy()->addSeconds(59));                  // 0
643echo $dt->diffInMinutes($dt->copy()->addSeconds(60));                  // 1
644echo $dt->diffInMinutes($dt->copy()->addSeconds(119));                 // 1
645echo $dt->diffInMinutes($dt->copy()->addSeconds(120));                 // 2
646
647// others that are defined
648// diffInYears(), diffInMonths(), diffInDays()
649// diffInHours(), diffInMinutes(), diffInSeconds()
650```
651```php
652// Carbon::average(Carbon $dt = null)
653```
654
655<a name="api-humandiff"/>
656### Difference for Humans
657
658It 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 a month being 4 weeks. The lone argument for the function is the other Carbon instance to diff against, and of course it defaults to `now()` if not specified.
659
660This method will add a phrase after the difference value relative to the instance and the passed in instance.  There are 4 possibilities:
661
662* When comparing a value in the past to default now:
663    * 1 hour ago
664    * 5 months ago
665
666* When comparing a value in the future to default now:
667    * 1 hour from now
668    * 5 months from now
669
670* When comparing a value in the past to another value:
671    * 1 hour before
672    * 5 months before
673
674* When comparing a value in the future to another value:
675    * 1 hour after
676    * 5 months after
677
678```php
679// The most typical usage is for comments
680// The instance is the date the comment was created and its being compared to default now()
681echo Carbon::now()->subDays(5)->diffForHumans();               // 5 days ago
682
683echo Carbon::now()->diffForHumans(Carbon::now()->subYear());   // 1 year after
684
685$dt = Carbon::createFromDate(2011, 2, 1);
686
687echo $dt->diffForHumans($dt->copy()->addMonth());              // 1 month before
688echo $dt->diffForHumans($dt->copy()->subMonth());              // 1 month after
689
690echo Carbon::now()->addSeconds(5)->diffForHumans();            // 5 seconds from now
691
692echo Carbon::now()->subDays(24)->diffForHumans();              // 3 weeks ago
693```
694
695<a name="api-modifiers"/>
696### Modifiers
697
698These 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.
699
700The only one slightly different is the `average()` function.  It moves your instance to the middle date between itself and the provided Carbon argument.
701
702```php
703$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
704echo $dt->startOfDay();                            // 2012-01-31 00:00:00
705
706$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
707echo $dt->endOfDay();                              // 2012-01-31 23:59:59
708
709$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
710echo $dt->startOfMonth();                          // 2012-01-01 00:00:00
711
712$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
713echo $dt->endOfMonth();                            // 2012-01-31 23:59:59
714
715$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
716echo $dt->startOfYear();                           // 2012-01-01 00:00:00
717
718$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
719echo $dt->endOfYear();                             // 2012-12-31 23:59:59
720
721$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
722echo $dt->startOfDecade();                         // 2010-01-01 00:00:00
723
724$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
725echo $dt->endOfDecade();                           // 2019-12-31 23:59:59
726
727$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
728echo $dt->startOfCentury();                        // 2000-01-01 00:00:00
729
730$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
731echo $dt->endOfCentury();                          // 2099-12-31 23:59:59
732
733$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
734echo $dt->startOfWeek();                           // 2012-01-30 00:00:00
735var_dump($dt->dayOfWeek == Carbon::MONDAY);        // bool(true) : ISO8601 week starts on Monday
736
737$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
738echo $dt->endOfWeek();                             // 2012-02-05 23:59:59
739var_dump($dt->dayOfWeek == Carbon::SUNDAY);        // bool(true) : ISO8601 week ends on Sunday
740
741$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
742echo $dt->next(Carbon::WEDNESDAY);                 // 2012-02-01 00:00:00
743var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)
744
745$dt = Carbon::create(2012, 1, 1, 12, 0, 0);
746echo $dt->next();                                  // 2012-01-08 00:00:00
747
748$dt = Carbon::create(2012, 1, 31, 12, 0, 0);
749echo $dt->previous(Carbon::WEDNESDAY);             // 2012-01-25 00:00:00
750var_dump($dt->dayOfWeek == Carbon::WEDNESDAY);     // bool(true)
751
752$dt = Carbon::create(2012, 1, 1, 12, 0, 0);
753echo $dt->previous();                              // 2011-12-25 00:00:00
754
755$start = Carbon::create(2014, 1, 1, 0, 0, 0);
756$end = Carbon::create(2014, 1, 30, 0, 0, 0);
757echo $start->average($end);                        // 2014-01-15 12:00:00
758
759// others that are defined that are similar
760//   firstOfMonth(), lastOfMonth(), nthOfMonth()
761//   firstOfQuarter(), lastOfQuarter(), nthOfQuarter()
762//   firstOfYear(), lastOfYear(), nthOfYear()
763
764```
765
766<a name="api-constants"/>
767### Constants
768
769The following constants are defined in the Carbon class.
770
771* SUNDAY = 0
772* MONDAY = 1
773* TUESDAY = 2
774* WEDNESDAY = 3
775* THURSDAY = 4
776* FRIDAY = 5
777* SATURDAY = 6
778* MONTHS_PER_YEAR = 12
779* HOURS_PER_DAY = 24
780* MINUTES_PER_HOUR = 60
781* SECONDS_PER_MINUTE = 60
782
783```php
784$dt = Carbon::createFromDate(2012, 10, 6);
785if ($dt->dayOfWeek === Carbon::SATURDAY) {
786    echo 'Place bets on Ottawa Senators Winning!';
787}
788```
789
790<a name="about"/>
791## About
792
793<a name="about-contributing"/>
794### Contributing
795
796I 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.
797
798> **Don't make changes to the `readme.md` directly!!**
799
800Change 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.
801
802The commands are quickly explained below.  To see some examples you can view the raw `readme.src.md` file in this repo.
803
804`{{::lint()}}`
805
806The `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.
807
808    {{::lint($var = 'brian nesbitt';)}} => $var = 'brian nesbitt';
809
810> 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.
811
812`{{varName::exec()}}` and `{{varName_eval}}`
813
814The `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.
815
816    {{exVarName::exec(echo $var;)}} => echo $var;
817    {{exVarName_eval}} => brian nesbitt  // $var is still set from above
818
819`/*pad()*/`
820
821The `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.
822
823    {{exVarName1::exec(echo 12345;/*pad(20)*/)}} // {{exVarName1_eval}}
824    {{exVarName2::exec(echo 6;/*pad(20)*/)}} // {{exVarName2_eval}}
825
826... would generate to:
827
828    echo 12345;          // 12345
829    echo 6;              // 6
830
831Apart from the readme the typical steps can be used to contribute your own improvements.
832
833* Fork
834* Clone
835* PHPUnit
836* Branch
837* PHPUnit
838* Code
839* PHPUnit
840* Commit
841* Push
842* Pull request
843* Relax and play Castle Crashers
844
845<a name="about-author"/>
846### Author
847
848Brian Nesbitt - <brian@nesbot.com> - <http://twitter.com/NesbittBrian>
849
850<a name="about-license"/>
851### License
852
853Carbon is licensed under the MIT License - see the `LICENSE` file for details
854
855<a name="about-history"/>
856### History
857
858You can view the history of the Carbon project in the [history file](https://github.com/briannesbitt/Carbon/blob/master/history.md).
859
860<a name="about-whyname"/>
861### Why the name Carbon?
862
863Read about [Carbon Dating](http://en.wikipedia.org/wiki/Radiocarbon_dating)
864
865![](https://cruel-carlota.pagodabox.com/55ce479cc1edc5e0cc5b4b6f9a7a9200)