PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/readme.md

https://github.com/michaelcaplan/Carbon
Markdown | 647 lines | 471 code | 176 blank | 0 comment | 0 complexity | 79166a9986ed803921bf098e475b6bce MD5 | raw file
  1. > **This file is autogenerated. Please see the [Contributing](#about-contributing) section from more information.**
  2. # Carbon
  3. [![Build Status](https://secure.travis-ci.org/briannesbitt/Carbon.png)](http://travis-ci.org/briannesbitt/Carbon)
  4. A simple API extension for DateTime with PHP 5.3+
  5. ```php
  6. printf("Right now is %s", Carbon::now()->toDateTimeString());
  7. printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); //implicit __toString()
  8. $tomorrow = Carbon::now()->addDay();
  9. $lastWeek = Carbon::now()->subWeek();
  10. $nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);
  11. $officialDate = Carbon::now()->toRFC2822String();
  12. $howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;
  13. $noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');
  14. $worldWillEnd = Carbon::createFromDate(2012, 12, 21, 'GMT');
  15. // comparisons are always done in UTC
  16. if (Carbon::now()->gte($worldWillEnd)) {
  17. die();
  18. }
  19. if (Carbon::now()->isWeekend()) {
  20. echo 'Party!';
  21. }
  22. echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
  23. // ... but also does 'from now', 'after' and 'before'
  24. // rolling up to seconds, minutes, hours, days, months, years
  25. $daysSinceEpoch = Carbon::createFromTimeStamp(0)->diffInDays();
  26. ```
  27. ## README Contents
  28. * [Installation](#install)
  29. * [Requirements](#requirements)
  30. * [With composer](#install-composer)
  31. * [Without composer](#install-nocomposer)
  32. * [API](#api)
  33. * [Instantiation](#api-instantiation)
  34. * [Getters](#api-getters)
  35. * [Setters](#api-setters)
  36. * [Fluent Setters](#api-settersfluent)
  37. * [IsSet](#api-isset)
  38. * [Formatting and Strings](#api-formatting)
  39. * [Common Formats](#api-commonformats)
  40. * [Comparison](#api-comparison)
  41. * [Addition and Subtraction](#api-addsub)
  42. * [Difference](#api-difference)
  43. * [Difference for Humans](#api-humandiff)
  44. * [Constants](#api-constants)
  45. * [About](#about)
  46. * [Contributing](#about-contributing)
  47. * [Author](#about-author)
  48. * [License](#about-license)
  49. * [History](#about-history)
  50. * [Why the name Carbon?](#about-whyname)
  51. <a name="install"/>
  52. ## Installation
  53. <a name="requirements"/>
  54. ### Requirements
  55. - Any flavour of PHP 5.3+ should do
  56. - [optional] PHPUnit to execute the test suite
  57. <a name="install-composer"/>
  58. ### With Composer
  59. The 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.
  60. ```json
  61. {
  62. "require": {
  63. "nesbot/Carbon": "*"
  64. }
  65. }
  66. ```
  67. ```php
  68. <?php
  69. require 'vendor/autoload.php';
  70. use Carbon\Carbon;
  71. printf("Now: %s", Carbon::now());
  72. ```
  73. <a name="install-nocomposer"/>
  74. ### Without Composer
  75. Why 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.
  76. ```php
  77. <?php
  78. require 'path/to/Carbon.php';
  79. use Carbon\Carbon;
  80. printf("Now: %s", Carbon::now());
  81. ```
  82. <a name="api"/>
  83. ## API
  84. The 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.
  85. ```php
  86. <?php
  87. class Carbon extends \DateTime
  88. {
  89. // code here
  90. }
  91. ```
  92. 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.
  93. > **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.**
  94. 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.
  95. ```php
  96. $dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto');
  97. $dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver');
  98. echo $dtVancouver->diffInHours($dtToronto); // 3
  99. ```
  100. 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.
  101. <a name="api-instantiation"/>
  102. ### Instantiation
  103. There 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.
  104. ```php
  105. $carbon = new Carbon(); // equivalent to Carbon::now()
  106. $carbon = new Carbon('first day of January 2008', 'America/Vancouver');
  107. echo get_class($carbon); // 'Carbon\Carbon'
  108. ```
  109. 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.
  110. ```php
  111. $now = Carbon::now();
  112. $nowInLondonTz = Carbon::now(new DateTimeZone('Europe/London'));
  113. // or just pass the timezone as a string
  114. $nowInLondonTz = Carbon::now('Europe/London');
  115. ```
  116. 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`.
  117. ```php
  118. $now = Carbon::now();
  119. echo $now; // 2012-10-14 20:40:20
  120. $today = Carbon::today();
  121. echo $today; // 2012-10-14 00:00:00
  122. $tomorrow = Carbon::tomorrow('Europe/London');
  123. echo $tomorrow; // 2012-10-16 00:00:00
  124. $yesterday = Carbon::yesterday();
  125. echo $yesterday; // 2012-10-13 00:00:00
  126. ```
  127. 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.
  128. ```php
  129. Carbon::createFromDate($year, $month, $day, $tz);
  130. Carbon::createFromTime($hour, $minute, $second, $tz);
  131. Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
  132. ```
  133. `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.
  134. ```php
  135. $xmasThisYear = Carbon::createFromDate(null, 12, 25); // Year defaults to current year
  136. $Y2K = Carbon::create(2000, 1, 1, 0, 0, 0);
  137. $alsoY2K = Carbon::create(1999, 12, 31, 24);
  138. $noonLondonTz = Carbon::createFromTime(12, 0, 0, 'Europe/London');
  139. // A two digit minute could not be found
  140. try { Carbon::create(1975, 5, 21, 22, -2, 0); } catch(InvalidArgumentException $x) { echo $x->getMessage(); }
  141. ```
  142. ```php
  143. Carbon::createFromFormat($format, $time, $tz);
  144. ```
  145. `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()`.
  146. ```php
  147. echo Carbon::createFromFormat('Y-m-d H', '1975-05-21 22')->toDateTimeString(); // 1975-05-21 22:00:00
  148. ```
  149. The 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.
  150. ```php
  151. echo Carbon::createFromTimeStamp(-1)->toDateTimeString(); // 1969-12-31 18:59:59
  152. echo Carbon::createFromTimeStamp(-1, 'Europe/London')->toDateTimeString(); // 1970-01-01 00:59:59
  153. echo Carbon::createFromTimeStampUTC(-1)->toDateTimeString(); // 1969-12-31 23:59:59
  154. ```
  155. 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.
  156. ```php
  157. $dt = Carbon::now();
  158. echo $dt->diffInYears($dt->copy()->addYear()); // 1
  159. // $dt was unchanged and still holds the value of Carbon:now()
  160. ```
  161. 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.
  162. ```php
  163. $dt = new \DateTime('first day of January 2008'); // <== instance from another API
  164. $carbon = Carbon::instance($dt);
  165. echo get_class($carbon); // 'Carbon\Carbon'
  166. echo $carbon->toDateTimeString(); // '2008-01-01 00:00:00'
  167. ```
  168. <a name="api-getters"/>
  169. ### Getters
  170. 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.
  171. ```php
  172. $dt = Carbon::create(2012, 9, 5, 23, 26, 11);
  173. // These getters specifically return integers, ie intval()
  174. var_dump($dt->year); // int(2012)
  175. var_dump($dt->month); // int(9)
  176. var_dump($dt->day); // int(5)
  177. var_dump($dt->hour); // int(23)
  178. var_dump($dt->minute); // int(26)
  179. var_dump($dt->second); // int(11)
  180. var_dump($dt->dayOfWeek); // int(3)
  181. var_dump($dt->dayOfYear); // int(248)
  182. var_dump($dt->weekOfYear); // int(36)
  183. var_dump($dt->daysInMonth); // int(30)
  184. var_dump($dt->timestamp); // int(1346901971)
  185. var_dump(Carbon::createFromDate(1975, 5, 21)->age); // int(37) calculated vs now in the same tz
  186. var_dump($dt->quarter); // int(3)
  187. // Returns an int of seconds difference from UTC (+/- sign included)
  188. var_dump(Carbon::createFromTimestampUTC(0)->offset); // int(0)
  189. var_dump(Carbon::createFromTimestamp(0)->offset); // int(-18000)
  190. // Returns an int of hours difference from UTC (+/- sign included)
  191. var_dump(Carbon::createFromTimestamp(0)->offsetHours); // int(-5)
  192. // Indicates if day light savings time is on
  193. var_dump(Carbon::createFromDate(2012, 1, 1)->dst); // bool(false)
  194. // Gets the DateTimeZone instance
  195. echo get_class(Carbon::now()->timezone); // DateTimeZone
  196. echo get_class(Carbon::now()->tz); // DateTimeZone
  197. // Gets the DateTimeZone instance name, shortcut for ->timezone->getName()
  198. echo Carbon::now()->timezoneName; // America/Toronto
  199. echo Carbon::now()->tzName; // America/Toronto
  200. ```
  201. <a name="api-setters"/>
  202. ### Setters
  203. 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.
  204. ```php
  205. $dt = Carbon::now();
  206. $dt->year = 1975;
  207. $dt->month = 13; // would force year++ and month = 1
  208. $dt->month = 5;
  209. $dt->day = 21;
  210. $dt->hour = 22;
  211. $dt->minute = 32;
  212. $dt->second = 5;
  213. $dt->timestamp = 169957925; // This will not change the timezone
  214. // Set the timezone via DateTimeZone instance or string
  215. $dt->timezone = new DateTimeZone('Europe/London');
  216. $dt->timezone = 'Europe/London';
  217. $dt->tz = 'Europe/London';
  218. ```
  219. <a name="api-settersfluent"/>
  220. ### Fluent Setters
  221. 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.
  222. ```php
  223. $dt = Carbon::now();
  224. $dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString();
  225. $dt->setDate(1975, 5, 21)->setTime(22, 32, 5)->toDateTimeString();
  226. $dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();
  227. $dt->timestamp(169957925)->timezone('Europe/London');
  228. $dt->tz('America/Toronto')->setTimezone('America/Vancouver');
  229. ```
  230. <a name="api-isset"/>
  231. ### IsSet
  232. 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).
  233. ```php
  234. var_dump(isset(Carbon::now()->iDoNotExist)); // bool(false)
  235. var_dump(isset(Carbon::now()->hour)); // bool(true)
  236. var_dump(empty(Carbon::now()->iDoNotExist)); // bool(true)
  237. var_dump(empty(Carbon::now()->year)); // bool(false)
  238. ```
  239. <a name="api-formatting"/>
  240. ### Formatting and Strings
  241. 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 defined which allows a Carbon instance to be printed as a pretty date time string when used in a string context.
  242. ```php
  243. $dt = Carbon::create(1975, 12, 25, 14, 15, 16);
  244. var_dump($dt->toDateTimeString() == $dt); // bool(true) => uses __toString()
  245. echo $dt->toDateString(); // 1975-12-25
  246. echo $dt->toFormattedDateString(); // Dec 25, 1975
  247. echo $dt->toTimeString(); // 14:15:16
  248. echo $dt->toDateTimeString(); // 1975-12-25 14:15:16
  249. echo $dt->toDayDateTimeString(); // Thu, Dec 25, 1975 2:15 PM
  250. // ... of course format() is still available
  251. echo $dt->format('l jS \\of F Y h:i:s A'); // Thursday 25th of December 1975 02:15:16 PM
  252. ```
  253. <a name="api-commonformats"/>
  254. ## Common Formats
  255. The following are wrappers for the common formats provided in the [DateTime class](http://www.php.net/manual/en/class.datetime.php).
  256. ```php
  257. $dt = Carbon::now();
  258. echo $dt->toATOMString(); // same as $dt->format(DateTime::ATOM);
  259. echo $dt->toCOOKIEString();
  260. echo $dt->toISO8601String();
  261. echo $dt->toRFC822String();
  262. echo $dt->toRFC850String();
  263. echo $dt->toRFC1036String();
  264. echo $dt->toRFC1123String();
  265. echo $dt->toRFC2822String();
  266. echo $dt->toRFC3339String();
  267. echo $dt->toRSSString();
  268. echo $dt->toW3CString();
  269. ```
  270. <a name="api-comparison"/>
  271. ### Comparison
  272. 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.
  273. ```php
  274. $first = Carbon::create(2012, 9, 5, 23, 26, 11);
  275. $second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');
  276. echo $first->toDateTimeString(); // 2012-09-05 23:26:11
  277. echo $second->toDateTimeString(); // 2012-09-05 20:26:11
  278. var_dump($first->eq($second)); // bool(true)
  279. var_dump($first->ne($second)); // bool(false)
  280. var_dump($first->gt($second)); // bool(false)
  281. var_dump($first->gte($second)); // bool(true)
  282. var_dump($first->lt($second)); // bool(false)
  283. var_dump($first->lte($second)); // bool(true)
  284. $first->setDateTime(2012, 1, 1, 0, 0, 0);
  285. $second->setDateTime(2012, 1, 1, 0, 0, 0); // Remember tz is 'America/Vancouver'
  286. var_dump($first->eq($second)); // bool(false)
  287. var_dump($first->ne($second)); // bool(true)
  288. var_dump($first->gt($second)); // bool(false)
  289. var_dump($first->gte($second)); // bool(false)
  290. var_dump($first->lt($second)); // bool(true)
  291. var_dump($first->lte($second)); // bool(true)
  292. ```
  293. 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.
  294. ```php
  295. $dt = Carbon::now();
  296. $dt->isWeekday();
  297. $dt->isWeekend();
  298. $dt->isYesterday();
  299. $dt->isToday();
  300. $dt->isTomorrow();
  301. $dt->isFuture();
  302. $dt->isPast();
  303. $dt->isLeapYear();
  304. ```
  305. <a name="api-addsub"/>
  306. ### Addition and Subtraction
  307. 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.
  308. ```php
  309. $dt = Carbon::create(2012, 1, 31, 0);
  310. echo $dt->toDateTimeString(); // 2012-01-31 00:00:00
  311. echo $dt->addYears(5); // 2017-01-31 00:00:00
  312. echo $dt->addYear(); // 2018-01-31 00:00:00
  313. echo $dt->subYear(); // 2017-01-31 00:00:00
  314. echo $dt->subYears(5); // 2012-01-31 00:00:00
  315. echo $dt->addMonths(60); // 2017-01-31 00:00:00
  316. echo $dt->addMonth(); // 2017-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps
  317. echo $dt->subMonth(); // 2017-02-03 00:00:00
  318. echo $dt->subMonths(60); // 2012-02-03 00:00:00
  319. echo $dt->addDays(29); // 2012-03-03 00:00:00
  320. echo $dt->addDay(); // 2012-03-04 00:00:00
  321. echo $dt->subDay(); // 2012-03-03 00:00:00
  322. echo $dt->subDays(29); // 2012-02-03 00:00:00
  323. echo $dt->addWeekdays(4); // 2012-02-09 00:00:00
  324. echo $dt->addWeekday(); // 2012-02-10 00:00:00
  325. echo $dt->subWeekday(); // 2012-02-09 00:00:00
  326. echo $dt->subWeekdays(4); // 2012-02-03 00:00:00
  327. echo $dt->addWeeks(3); // 2012-02-24 00:00:00
  328. echo $dt->addWeek(); // 2012-03-02 00:00:00
  329. echo $dt->subWeek(); // 2012-02-24 00:00:00
  330. echo $dt->subWeeks(3); // 2012-02-03 00:00:00
  331. echo $dt->addHours(24); // 2012-02-04 00:00:00
  332. echo $dt->addHour(); // 2012-02-04 01:00:00
  333. echo $dt->subHour(); // 2012-02-04 00:00:00
  334. echo $dt->subHours(24); // 2012-02-03 00:00:00
  335. echo $dt->addMinutes(61); // 2012-02-03 01:01:00
  336. echo $dt->addMinute(); // 2012-02-03 01:02:00
  337. echo $dt->subMinute(); // 2012-02-03 01:01:00
  338. echo $dt->subMinutes(61); // 2012-02-03 00:00:00
  339. echo $dt->addSeconds(61); // 2012-02-03 00:01:01
  340. echo $dt->addSecond(); // 2012-02-03 00:01:02
  341. echo $dt->subSecond(); // 2012-02-03 00:01:01
  342. echo $dt->subSeconds(61); // 2012-02-03 00:00:00
  343. $dt = Carbon::create(2012, 1, 31, 12, 0, 0);
  344. echo $dt->startOfDay(); // 2012-01-31 00:00:00
  345. $dt = Carbon::create(2012, 1, 31, 12, 0, 0);
  346. echo $dt->endOfDay(); // 2012-01-31 23:59:59
  347. $dt = Carbon::create(2012, 1, 31, 12, 0, 0);
  348. echo $dt->startOfMonth(); // 2012-01-01 00:00:00
  349. $dt = Carbon::create(2012, 1, 31, 12, 0, 0);
  350. echo $dt->endOfMonth(); // 2012-01-31 23:59:59
  351. ```
  352. For fun you can also pass negative values to `addXXX()`, in fact that's how `subXXX()` is implemented.
  353. <a name="api-difference"/>
  354. ### Difference
  355. 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.
  356. ```php
  357. // Carbon::diffInYears(Carbon $dt = null, $abs = true)
  358. echo Carbon::now('America/Vancouver')->diffInSeconds(Carbon::now('Europe/London')); // 0
  359. $dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
  360. $dtVancouver = Carbon::createFromDate(2000, 1, 1, 'America/Vancouver');
  361. echo $dtOttawa->diffInHours($dtVancouver); // 3
  362. echo $dtOttawa->diffInHours($dtVancouver, false); // 3
  363. echo $dtVancouver->diffInHours($dtOttawa, false); // -3
  364. $dt = Carbon::create(2012, 1, 31, 0);
  365. echo $dt->diffInDays($dt->copy()->addMonth()); // 31
  366. echo $dt->diffInDays($dt->copy()->subMonth(), false); // -31
  367. $dt = Carbon::create(2012, 4, 30, 0);
  368. echo $dt->diffInDays($dt->copy()->addMonth()); // 30
  369. echo $dt->diffInDays($dt->copy()->addWeek()); // 7
  370. $dt = Carbon::create(2012, 1, 1, 0);
  371. echo $dt->diffInMinutes($dt->copy()->addSeconds(59)); // 0
  372. echo $dt->diffInMinutes($dt->copy()->addSeconds(60)); // 1
  373. echo $dt->diffInMinutes($dt->copy()->addSeconds(119)); // 1
  374. echo $dt->diffInMinutes($dt->copy()->addSeconds(120)); // 2
  375. // others that are defined
  376. // diffInYears(), diffInMonths(), diffInDays()
  377. // diffInHours(), diffInMinutes(), diffInSeconds()
  378. ```
  379. <a name="api-humandiff"/>
  380. ### Difference for Humans
  381. 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.
  382. This method will add a phrase after the difference value relative to the instance and the passed in instance. There are 4 possibilities:
  383. * When comparing a value in the past to default now:
  384. * 1 hour ago
  385. * 5 months ago
  386. * When comparing a value in the future to default now:
  387. * 1 hour from now
  388. * 5 months from now
  389. * When comparing a value in the past to another value:
  390. * 1 hour before
  391. * 5 months before
  392. * When comparing a value in the future to another value:
  393. * 1 hour after
  394. * 5 months after
  395. ```php
  396. // The most typical usage is for comments
  397. // The instance is the date the comment was created and its being compared to default now()
  398. echo Carbon::now()->subDays(5)->diffForHumans(); // 5 days ago
  399. echo Carbon::now()->diffForHumans(Carbon::now()->subYear()); // 1 year after
  400. $dt = Carbon::createFromDate(2011, 2, 1);
  401. echo $dt->diffForHumans($dt->copy()->addMonth()); // 28 days before
  402. echo $dt->diffForHumans($dt->copy()->subMonth()); // 1 month after
  403. echo Carbon::now()->addSeconds(5)->diffForHumans(); // 5 seconds from now
  404. ```
  405. <a name="api-constants"/>
  406. ### Constants
  407. The following constants are defined in the Carbon class.
  408. * SUNDAY = 0
  409. * MONDAY = 1
  410. * TUESDAY = 2
  411. * WEDNESDAY = 3
  412. * THURSDAY = 4
  413. * FRIDAY = 5
  414. * SATURDAY = 6
  415. * MONTHS_PER_YEAR = 12
  416. * HOURS_PER_DAY = 24
  417. * MINUTES_PER_HOUR = 60
  418. * SECONDS_PER_MINUTE = 60
  419. ```php
  420. $dt = Carbon::createFromDate(2012, 10, 6);
  421. if ($dt->dayOfWeek === Carbon::SATURDAY) {
  422. echo 'Place bets on Ottawa Senators Winning!';
  423. }
  424. ```
  425. <a name="about"/>
  426. ## About
  427. <a name="about-contributing"/>
  428. ### Contributing
  429. 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.
  430. > **Don't make changes to the `readme.md` directly!!**
  431. 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.
  432. The commands are quickly explained below. To see some examples you can view the raw `readme.src.md` file in this repo.
  433. `{{::lint()}}`
  434. 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.
  435. {{::lint($var = 'brian nesbitt';)}} => $var = 'brian nesbitt';
  436. > 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.
  437. `{{varName::exec()}}` and `{{varName_eval}}`
  438. 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.
  439. {{exVarName::exec(echo $var;)}} => echo $var;
  440. {{exVarName_eval}} => brian nesbitt // $var is still set from above
  441. `/*pad()*/`
  442. 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.
  443. {{exVarName1::exec(echo 12345;/*pad(20)*/)}} // {{exVarName1_eval}}
  444. {{exVarName2::exec(echo 6;/*pad(20)*/)}} // {{exVarName2_eval}}
  445. ... would generate to:
  446. echo 12345; // 12345
  447. echo 6; // 6
  448. Apart from the readme the typical steps can be used to contribute your own improvements.
  449. * Fork
  450. * Clone
  451. * PHPUnit
  452. * Branch
  453. * PHPUnit
  454. * Code
  455. * PHPUnit
  456. * Commit
  457. * Push
  458. * Pull request
  459. * Relax and play Castle Crashers
  460. <a name="about-author"/>
  461. ### Author
  462. Brian Nesbitt - <brian@nesbot.com> - <http://twitter.com/NesbittBrian>
  463. <a name="about-license"/>
  464. ### License
  465. Carbon is licensed under the MIT License - see the `LICENSE` file for details
  466. <a name="about-history"/>
  467. ### History
  468. You can view the history of the Carbon project in the [history file](https://github.com/briannesbitt/Carbon/blob/master/history.md).
  469. <a name="about-whyname"/>
  470. ### Why the name Carbon?
  471. Read about [Carbon Dating](http://en.wikipedia.org/wiki/Radiocarbon_dating)