Chronos

Chronos provides a zero-dependency collection of extensions to the DateTimeobject. In addition to convenience methods, Chronos provides:

  • Date objects for representing calendar dates.
  • Immutable date and datetime objects.
  • A pluggable translation system. Only English translations are included in thelibrary. However, cakephp/i18n can be used for full language support.

Installation

To install Chronos, you should use composer. From yourapplication’s ROOT directory (where composer.json file is located) run thefollowing:

  1. php composer.phar require "cakephp/chronos:^2.0"

Overview

Chronos provides a number of extensions to the DateTime objects provided by PHP.Chronos provides 5 classes that cover mutable and immutable date/time variantsand extensions to DateInterval.

  • Cake\Chronos\Chronos is an immutable date and time object.
  • Cake\Chronos\Date is a immutable date object.
  • Cake\Chronos\MutableDateTime is a mutable date and time object.
  • Cake\Chronos\MutableDate is a mutable date object.
  • Cake\Chronos\ChronosInterval is an extension to the DateIntervalobject.

Lastly, if you want to typehint against Chronos-provided date/time objects youshould use Cake\Chronos\ChronosInterface. All of the date and time objectsimplement this interface.

Creating Instances

There are many ways to get an instance of Chronos or Date. There are a number offactory methods that work with different argument sets:

  1. use Cake\Chronos\Chronos;
  2.  
  3. $now = Chronos::now();
  4. $today = Chronos::today();
  5. $yesterday = Chronos::yesterday();
  6. $tomorrow = Chronos::tomorrow();
  7.  
  8. // Parse relative expressions
  9. $date = Chronos::parse('+2 days, +3 hours');
  10.  
  11. // Date and time integer values.
  12. $date = Chronos::create(2015, 12, 25, 4, 32, 58);
  13.  
  14. // Date or time integer values.
  15. $date = Chronos::createFromDate(2015, 12, 25);
  16. $date = Chronos::createFromTime(11, 45, 10);
  17.  
  18. // Parse formatted values.
  19. $date = Chronos::createFromFormat('m/d/Y', '06/15/2015');

Working with Immutable Objects

If you’ve used PHP’s DateTime objects, you’re comfortable with _mutable_objects. Chronos offers mutable objects, but it also provides _immutable_objects. Immutable objects create copies of objects each time an object ismodified. Because modifier methods around datetimes are not always transparent,data can be modified accidentally or without the developer knowing.Immutable objects prevent accidental changes todata, and make code free of order-based dependency issues. Immutabilitydoes mean that you will need to remember to replace variables when usingmodifiers:

  1. // This code doesn't work with immutable objects
  2. $time->addDay(1);
  3. doSomething($time);
  4. return $time;
  5.  
  6. // This works like you'd expect
  7. $time = $time->addDay(1);
  8. $time = doSomething($time);
  9. return $time;

By capturing the return value of each modification your code will work asexpected. If you ever have an immutable object, and want to create a mutableone, you can use toMutable():

  1. $inplace = $time->toMutable();

Date Objects

PHP only provides a single DateTime object. Representing calendar dates can bea bit awkward with this class as it includes timezones, and time components thatdon’t really belong in the concept of a ‘day’. Chronos provides a Dateobject that allows you to represent dates. The time and timezone for theseobjects is always fixed to 00:00:00 UTC and all formatting/differencemethods operate at the day resolution:

  1. use Cake\Chronos\Date;
  2.  
  3. $today = Date::today();
  4.  
  5. // Changes to the time/timezone are ignored.
  6. $today->modify('+1 hours');
  7.  
  8. // Outputs '2015-12-20'
  9. echo $today;

Although Date uses a fixed time zone internally, you can specify whichtime zone to use for current time such as now() or today():

  1. use Cake\Chronos\Date:
  2.  
  3. // Takes the current date from Asia/Tokyo time zone
  4. $today = Date::today('Asia/Tokyo');

Modifier Methods

Chronos objects provide modifier methods that let you modify the value ina granular way:

  1. // Set components of the datetime value.
  2. $halloween = Chronos::create()
  3. ->year(2015)
  4. ->month(10)
  5. ->day(31)
  6. ->hour(20)
  7. ->minute(30);

You can also modify parts of the datetime relatively:

  1. $future = Chronos::create()
  2. ->addYear(1)
  3. ->subMonth(2)
  4. ->addDays(15)
  5. ->addHours(20)
  6. ->subMinutes(2);

It is also possible to make big jumps to defined points in time:

  1. $time = Chronos::create();
  2. $time->startOfDay();
  3. $time->endOfDay();
  4. $time->startOfMonth();
  5. $time->endOfMonth();
  6. $time->startOfYear();
  7. $time->endOfYear();
  8. $time->startOfWeek();
  9. $time->endOfWeek();

Or jump to specific days of the week:

  1. $time->next(ChronosInterface::TUESDAY);
  2. $time->previous(ChronosInterface::MONDAY);

When modifying dates/times across DST transitionsyour operations may gain/lose an additional hours resulting in hour values thatdon’t add up. You can avoid these issues by first changing your timezone toUTC, modifying the time:

  1. // Additional hour gained.
  2. $time = new Chronos('2014-03-30 00:00:00', 'Europe/London');
  3. debug($time->modify('+24 hours')); // 2014-03-31 01:00:00
  4.  
  5. // First switch to UTC, and modify
  6. $time = $time->setTimezone('UTC')
  7. ->modify('+24 hours');

Once you are done modifying the time you can add the original timezone to getthe localized time.

Comparison Methods

Once you have 2 instances of Chronos date/time objects you can compare them ina variety of ways:

  1. // Full suite of comparators exist
  2. // ne, gt, lt, lte.
  3. $first->eq($second);
  4. $first->gte($second);
  5.  
  6. // See if the current object is between two others.
  7. $now->between($start, $end);
  8.  
  9. // Find which argument is closest or farthest.
  10. $now->closest($june, $november);
  11. $now->farthest($june, $november);

You can also inquire about where a given value falls on the calendar:

  1. $now->isToday();
  2. $now->isYesterday();
  3. $now->isFuture();
  4. $now->isPast();
  5.  
  6. // Check the day of the week
  7. $now->isWeekend();
  8.  
  9. // All other weekday methods exist too.
  10. $now->isMonday();

You can also find out if a value was within a relative time period:

  1. $time->wasWithinLast('3 days');
  2. $time->isWithinNext('3 hours');

Generating Differences

In addition to comparing datetimes, calculating differences or deltas betweentwo values is a common task:

  1. // Get a DateInterval representing the difference
  2. $first->diff($second);
  3.  
  4. // Get difference as a count of specific units.
  5. $first->diffInHours($second);
  6. $first->diffInDays($second);
  7. $first->diffInWeeks($second);
  8. $first->diffInYears($second);

You can generate human readable differences suitable for use in a feed ortimeline:

  1. // Difference from now.
  2. echo $date->diffForHumans();
  3.  
  4. // Difference from another point in time.
  5. echo $date->diffForHumans($other); // 1 hour ago;

Formatting Strings

Chronos provides a number of methods for displaying our outputting datetimeobjects:

  1. // Uses the format controlled by setToStringFormat()
  2. echo $date;
  3.  
  4. // Different standard formats
  5. echo $time->toAtomString(); // 1975-12-25T14:15:16-05:00
  6. echo $time->toCookieString(); // Thursday, 25-Dec-1975 14:15:16 EST
  7. echo $time->toIso8601String(); // 1975-12-25T14:15:16-05:00
  8. echo $time->toRfc822String(); // Thu, 25 Dec 75 14:15:16 -0500
  9. echo $time->toRfc850String(); // Thursday, 25-Dec-75 14:15:16 EST
  10. echo $time->toRfc1036String(); // Thu, 25 Dec 75 14:15:16 -0500
  11. echo $time->toRfc1123String(); // Thu, 25 Dec 1975 14:15:16 -0500
  12. echo $time->toRfc2822String(); // Thu, 25 Dec 1975 14:15:16 -0500
  13. echo $time->toRfc3339String(); // 1975-12-25T14:15:16-05:00
  14. echo $time->toRssString(); // Thu, 25 Dec 1975 14:15:16 -0500
  15. echo $time->toW3cString(); // 1975-12-25T14:15:16-05:00
  16.  
  17. // Get the quarter/week
  18. echo $time->toQuarter(); // 4
  19. echo $time->toWeek(); // 52
  20.  
  21. // Generic formatting
  22. echo $time->toTimeString(); // 14:15:16
  23. echo $time->toDateString(); // 1975-12-25
  24. echo $time->toDateTimeString(); // 1975-12-25 14:15:16
  25. echo $time->toFormattedDateString(); // Dec 25, 1975
  26. echo $time->toDayDateTimeString(); // Thu, Dec 25, 1975 2:15 PM

Extracting Date Components

Getting parts of a date object can be done by directly accessing properties:

  1. $time = new Chronos('2015-12-31 23:59:58.123');
  2. $time->year; // 2015
  3. $time->month; // 12
  4. $time->day; // 31
  5. $time->hour // 23
  6. $time->minute // 59
  7. $time->second // 58
  8. $time->micro // 123

Other properties that can be accessed are:

  • timezone
  • timezoneName
  • dayOfWeek
  • dayOfMonth
  • dayOfYear
  • daysInMonth
  • timestamp
  • quarter

Testing Aids

When writing unit tests, it is helpful to fixate the current time. Chronos letsyou fix the current time for each class. As part of your test suite’s bootstrapprocess you can include the following:

  1. Chronos::setTestNow(Chronos::now());
  2. MutableDateTime::setTestNow(MutableDateTime::now());
  3. Date::setTestNow(Date::now());
  4. MutableDate::setTestNow(MutableDate::now());

This will fix the current time of all objects to be the point at which the testsuite started.

For example, if you fixate the Chronos to some moment in the past, any newinstance of Chronos created with now or a relative time string, will bereturned relative to the fixated time:

  1. Chronos::setTestNow(new Chronos('1975-12-25 00:00:00'));
  2.  
  3. $time = new Chronos(); // 1975-12-25 00:00:00
  4. $time = new Chronos('1 hour ago'); // 1975-12-24 23:00:00

To reset the fixation, simply call setTestNow() again with no parameter orwith null as a parameter.