Date & Time

class Cake\I18n\DateTime

If you need TimeHelper functionalities outside of a View, use the DateTime class:

use Cake\I18n\DateTime;

class UsersController extends AppController
    public function initialize(): void

    public function afterLogin()
        $identity = $this->Authentication->getIdentity();
        $time = new DateTime($identity->date_of_birth);
        if ($time->isToday()) {
            // Greet user with a happy birthday message
            $this->Flash->success(__('Happy birthday to you...'));

Under the hood, CakePHP uses Chronos to power its DateTime utility. Anything you can do with Chronos and PHP’s DateTime, you can do with DateTime and Date.

For more details on Chronos please see the API documentation.

Creating DateTime Instances

DateTime are immutable objects that are useful when you want to prevent accidental changes to data, or when you want to avoid order based dependency issues.

There are a few ways to create DateTime instances:

use Cake\I18n\DateTime;

// Create from a string datetime.
$time = DateTime::createFromFormat(
    'Y-m-d H:i:s',
    '2021-01-31 22:11:30',

// Create from a timestamp and set timezone
$time = DateTime::createFromTimestamp(1612149090, 'America/New_York');

// Get the current time.
$time = DateTime::now();

// Or just use 'new'
$time = new DateTime('2021-01-31 22:11:30', 'America/New_York');

$time = new DateTime('2 hours ago');

The DateTime class constructor can take any parameter that the internal DateTimeImmutable PHP class can. When passing a number or numeric string, it will be interpreted as a UNIX timestamp.

In test cases, you can mock out now() using setTestNow():

// Fixate time.
$time = new DateTime('2021-01-31 22:11:30');

// Outputs '2021-01-31 22:11:30'
$now = DateTime::now();
echo $now->i18nFormat('yyyy-MM-dd HH:mm:ss');

// Outputs '2021-01-31 22:11:30'
$now = DateTime::parse('now');
echo $now->i18nFormat('yyyy-MM-dd HH:mm:ss');


Remember, DateTime instance always return a new instance from setters instead of modifying itself:

$time = DateTime::now();

// Create and reassign a new instance
$newTime = $time->year(2013)
// Outputs '2013-10-31 22:11:30'
echo $newTime->i18nFormat('yyyy-MM-dd HH:mm:ss');

You can also use the methods provided by PHP’s built-in DateTime class:

$time = $time->setDate(2013, 10, 31);

Failing to reassign the new DateTime instances will result in the original, unmodified instance being used:

// Outputs '2021-01-31 22:11:30'
echo $time->i18nFormat('yyyy-MM-dd HH:mm:ss');

You can create another instance with modified dates, through subtraction and addition of their components:

$time = DateTime::create(2021, 1, 31, 22, 11, 30);
$newTime = $time->subDays(5)
// Outputs '2/26/21, 8:11 PM'
echo $newTime;

// Using strtotime strings.
$newTime = $time->modify('+1 month -5 days -2 hours');
// Outputs '2/26/21, 8:11 PM'
echo $newTime;

You can get the internal components of a date by accessing its properties:

$time = DateTime::create(2021, 1, 31, 22, 11, 30);
echo $time->year; // 2021
echo $time->month; // 1
echo $time->day; // 31
echo $time->timezoneName; // America/New_York


static Cake\I18n\DateTime::setJsonEncodeFormat($format)

This method sets the default format used when converting an object to json:

DateTime::setJsonEncodeFormat('yyyy-MM-dd HH:mm:ss');  // For any immutable DateTime
Date::setJsonEncodeFormat('yyyy-MM-dd HH:mm:ss');  // For any mutable Date

$time = DateTime::parse('2021-01-31 22:11:30');
echo json_encode($time);   // Outputs '2021-01-31 22:11:30'

Date::setJsonEncodeFormat(static function($time) {
    return $time->format(DATE_ATOM);


This method must be called statically.


Be aware that this is not a PHP Datetime string format! You need to use a ICU date formatting string as specified in the following resource:

Changed in version 4.1.0: The callable parameter type was added.

Cake\I18n\DateTime::i18nFormat($format = null, $timezone = null, $locale = null)

A very common thing to do with Time instances is to print out formatted dates. CakePHP makes this a snap:

$time = DateTime::parse('2021-01-31 22:11:30');

// Prints a localized datetime stamp. Outputs '1/31/21, 10:11 PM'
echo $time;

// Outputs '1/31/21, 10:11 PM' for the en-US locale
echo $time->i18nFormat();

// Use the full date and time format. Outputs 'Sunday, January 31, 2021 at 10:11:30 PM Eastern Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL);

// Use full date but short time format. Outputs 'Sunday, January 31, 2021 at 10:11 PM'
echo $time->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]);

// Outputs '2021-Jan-31 22:11:30'
echo $time->i18nFormat('yyyy-MMM-dd HH:mm:ss');

It is possible to specify the desired format for the string to be displayed. You can either pass IntlDateFormatter constants as the first argument of this function, or pass a full ICU date formatting string as specified in the following resource:

You can also format dates with non-gregorian calendars:

// On ICU version 66.1
$time = DateTime::create(2021, 1, 31, 22, 11, 30);

// Outputs 'Sunday, Bahman 12, 1399 AP at 10:11:30 PM Eastern Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL, null, 'en-IR@calendar=persian');

// Outputs 'Sunday, January 31, 3 Reiwa at 10:11:30 PM Eastern Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL, null, 'en-JP@calendar=japanese');

// Outputs 'Sunday, Twelfth Month 19, 2020(geng-zi) at 10:11:30 PM Eastern Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL, null, 'en-CN@calendar=chinese');

// Outputs 'Sunday, Jumada II 18, 1442 AH at 10:11:30 PM Eastern Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL, null, 'en-SA@calendar=islamic');

The following calendar types are supported:

  • japanese

  • buddhist

  • chinese

  • persian

  • indian

  • islamic

  • hebrew

  • coptic

  • ethiopic


For constant strings i.e. IntlDateFormatter::FULL Intl uses ICU library that feeds its data from CLDR ( which version may vary depending on PHP installation and give different results.


Print out a predefined ‘nice’ format:

$time = DateTime::parse('2021-01-31 22:11:30', new \DateTimeZone('America/New_York'));

// Outputs 'Jan 31, 2021, 10:11 PM' in en-US
echo $time->nice();

You can alter the timezone in which the date is displayed without altering the DateTime object itself. This is useful when you store dates in one timezone, but want to display them in a user’s own timezone:

// Outputs 'Monday, February 1, 2021 at 4:11:30 AM Central European Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Paris');

// Outputs 'Monday, February 1, 2021 at 12:11:30 PM Japan Standard Time'
echo $time->i18nFormat(\IntlDateFormatter::FULL, 'Asia/Tokyo');

// Timezone is unchanged. Outputs 'America/New_York'
echo $time->timezoneName;

Leaving the first parameter as null will use the default formatting string:

// Outputs '2/1/21, 4:11 AM'
echo $time->i18nFormat(null, 'Europe/Paris');

Finally, it is possible to use a different locale for displaying a date:

// Outputs 'lundi 1 février 2021 à 04:11:30 heure normale d’Europe centrale'
echo $time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Paris', 'fr-FR');

// Outputs '1 févr. 2021 à 04:11'
echo $time->nice('Europe/Paris', 'fr-FR');

Setting the Default Locale and Format String

The default locale in which dates are displayed when using nice i18nFormat is taken from the directive intl.default_locale. You can, however, modify this default at runtime:


// Outputs '31 ene. 2021 22:11'
echo $time->nice();

From now on, datetimes will be displayed in the Spanish preferred format unless a different locale is specified directly in the formatting method.

Likewise, it is possible to alter the default formatting string to be used for i18nFormat:

DateTime::setToStringFormat(\IntlDateFormatter::SHORT); // For any DateTime
Date::setToStringFormat(\IntlDateFormatter::SHORT); // For any Date

// The same method exists on Date, and DateTime
// Outputs 'Sunday, January 31, 2021 at 10:11 PM'
echo $time;

// The same method exists on Date and DateTime
DateTime::setToStringFormat("EEEE, MMMM dd, yyyy 'at' KK:mm:ss a");
// Outputs 'Sunday, January 31, 2021 at 10:11:30 PM'
echo $time;

It is recommended to always use the constants instead of directly passing a date format string.


Be aware that this is not a PHP Datetime string format! You need to use a ICU date formatting string as specified in the following resource:

Formatting Relative Times

Cake\I18n\DateTime::timeAgoInWords(array $options = [])

Often it is useful to print times relative to the present:

$time = new DateTime('Jan 31, 2021');
// On June 12, 2021, this would output '4 months, 1 week, 6 days ago'
echo $time->timeAgoInWords(
    ['format' => 'MMM d, YYY', 'end' => '+1 year']

The end option lets you define at which point after which relative times should be formatted using the format option. The accuracy option lets us control what level of detail should be used for each interval range:

// Outputs '4 months ago'
echo $time->timeAgoInWords([
    'accuracy' => ['month' => 'month'],
    'end' => '1 year'

By setting accuracy to a string, you can specify what is the maximum level of detail you want output:

$time = new DateTime('+23 hours');
// Outputs 'in about a day'
echo $time->timeAgoInWords([
    'accuracy' => 'day'



Once created, you can convert DateTime instances into timestamps or quarter values:

$time = new DateTime('2021-01-31');
echo $time->toQuarter();  // Outputs '1'
echo $time->toUnixString();  // Outputs '1612069200'

Comparing With the Present


You can compare a DateTime instance with the present in a variety of ways:

$time = new DateTime('+3 days');


Each of the above methods will return true/false based on whether or not the DateTime instance matches the present.

Comparing With Intervals


You can see if a DateTime instance falls within a given range using wasWithinLast() and isWithinNext():

$time = new DateTime('+3 days');

// Within 2 days. Outputs 'false'
debug($time->isWithinNext('2 days'));

// Within 2 next weeks. Outputs 'true'
debug($time->isWithinNext('2 weeks'));

You can also compare a DateTime instance within a range in the past:

$time = new DateTime('-72 hours');

// Within past 2 days. Outputs 'false'
debug($time->wasWithinLast('2 days'));

// Within past 3 days. Outputs 'true'
debug($time->wasWithinLast('3 days'));

// Within past 2 weeks. Outputs 'true'
debug($time->wasWithinLast('2 weeks'));


The immutable Date class in CakePHP implements a similar API and methods as Cake\I18n\DateTime does. The main difference between DateTime and Date is that Date does not track time components. As an example:

use Cake\I18n\Date;

$date = new Date('2021-01-31');

$newDate = $date->modify('+2 hours');
// Outputs '2021-01-31 00:00:00'
echo $newDate->format('Y-m-d H:i:s');

$newDate = $date->addHours(36);
// Outputs '2021-01-31 00:00:00'
echo $newDate->format('Y-m-d H:i:s');

$newDate = $date->addDays(10);
// Outputs '2021-02-10 00:00:00'
echo $newDate->format('Y-m-d H:i:s');

Attempts to modify the timezone on a Date instance are also ignored:

use Cake\I18n\Date;
$date = new Date('2021-01-31', new \DateTimeZone('America/New_York'));
$newDate = $date->setTimezone(new \DateTimeZone('Europe/Berlin'));

// Outputs 'America/New_York'
echo $newDate->format('e');

Mutable Dates and Times

class Cake\I18n\Time
class Cake\I18n\Date

CakePHP uses mutable date and time classes that implement the same interface as their immutable siblings. Immutable objects are useful when you want to prevent accidental changes to data, or when you want to avoid order based dependency issues. Take the following code:

use Cake\I18n\Time;
$time = new Time('2015-06-15 08:23:45');
$time->modify('+2 hours');

// This method also modifies the $time instance

// Output here is unknown.
echo $time->format('Y-m-d H:i:s');

If the method call was re-ordered, or if someOtherFunction changed the output could be unexpected. The mutability of our object creates temporal coupling. If we were to use immutable objects, we could avoid this issue:

use Cake\I18n\DateTime;
$time = new DateTime('2015-06-15 08:23:45');
$time = $time->modify('+2 hours');

// This method's modifications don't change $time

// Output here is known.
echo $time->format('Y-m-d H:i:s');

Immutable dates and times are useful in entities as they prevent accidental modifications, and force changes to be explicit. Using immutable objects helps the ORM to more easily track changes, and ensure that date and datetime columns are persisted correctly:

// This change will be lost when the article is saved.
$article->updated->modify('+1 hour');

// By replacing the time object the property will be saved.
$article->updated = $article->updated->modify('+1 hour');

Accepting Localized Request Data

When creating text inputs that manipulate dates, you’ll probably want to accept and parse localized datetime strings. See the Parsing Localized Datetime Data.

Supported Timezones

CakePHP supports all valid PHP timezones. For a list of supported timezones, see this page.