Working with Mutable and Immutable DateTime in PHP

Published on by

Working with Mutable and Immutable DateTime in PHP image

Mutable dates can be the source of confusion and unexpected bugs in your code. My goal isn’t to tell you that DateTime is evil because it’s mutable, but to consider the tradeoffs and benefits of using mutable versus immutable DateTime objects. Either approach warrants a good test suite and an awareness of how modifier methods affect your date objects.

Until recently, I wasn’t even aware that PHP offers a counterpart to the DateTime class: DateTimeImmutable. The DateTimeIummtable class works just like the DateTime class, except that it never modifies itself, but returns a new object instead. So if you know how to work with DateTime, you immediately can work with DateTimeImmutable.

Working with Mutable DateTime Objects in PHP

Fortunately for us mere mortals, we can further abstract away these classes and work with libraries like Carbon. Later on, I’ll introduce you to a similar immutable library on top of DateTimeIummtable.

Carbon extends the mutable variety of DateTime which means that as you pass around a Carbon instance any modifier calls to it (i.e., addDay()) will result in change:

$person = Person::find(1);
echo $person->born // 1998-05-29 02:35:53
$person->born->addDay(1);
echo $person->born // 1998-05-30 02:35:53
$person->save();

In the context of an Eloquent model, this makes perfect sense. Otherwise, we’d have this weird assignment any time that we want to update a date using the immutable approach:

// This code doesn't work, it's what it would look like if Carbon instances were immutable
$newBirthday = $person->born->addDay(1);
$person->born = $newBirthday;
 
// Or...
$person->born = $person->born->addDay(1);

If you intend to do some comparison checking that takes modifications, you’d need to make a copy of this date to avoid mutating the original attribute. For example, this will mutate the model attribute:

function birthdayIsTomorrow($birthday) {
return $birthday->addDay(1)->isTomorrow();
}
 
// Mutation takes place...
if (birthdayIsTomorrow($person->born)) {
 
}
 
// No mutation takes place...
if (birthdayIsTomorrow($person->born->copy())) {
 
}
 
// Via clone, no mutation takes place...
if (birthdayIsTomorrow(clone $person->born)) {
 
}

The other interesting thing here is that if your code mutates the date, but you don’t save() the model, you might have a weird edge-case bug that’s hard to track down. The big takeaway here is to be aware of how code mutates your dates, and pass a copy of the date instead of a whole model to a method that needs to make modifications to the date.

I am not trying to argue that using the mutable library like Carbon is wrong; I am focusing on demonstrating how this style of object behaves and defensive techniques you must apply to avoid unexpected mutation.

Working with Immutable DateTime Objects in PHP

If you like working with Carbon, and you want to experiment with an immutable version that has a similar API, you might be interested in the Chronos library by the CakePHP foundation. Chronos was initially based off of Carbon, and is a stand-alone library without any external dependencies outside of PHP version ^5.5.9|^7.

Additionally, Chronos contains mutable date/time variants, totaling in five classes:

  • Cake\Chronos\Chronos is an immutable date and time object.
  • Cake\Chronos\Date is an 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 DateInterval object.

Using Chronos in the previous code example, the date object isn’t concerned with mutation because any change returns a new object:

if (birthdayIsTomorrow($person->born)) {
// Immutable, $person->born would equal `today` still
}

Every time you modify an object, a new copy is returned, making your code free from order-based dependency issues. Take the following example:

// i.e., 2018-05-29 04:23:01.342143
$meeting = \Cake\Chronos\Chronos::tomorrow();
$meeting->addDay(1); // Returns a new object
 
// No mutation, it returns the original 2018-05-29...
return $meeting;

To work with immutable dates, you need to replace the variable when working with modifiers:

$meeting = \Cake\Chronos\Chronos::tomorrow();
$meeting = $meeting->addDay(1);
 
// Returns 2018-05-30...
return $meeting

Even if you want to reset the date to the start of the day, you would need to do the same, or chain it to the original assignment:

// Assignment
$meeting = \Cake\Chronos\Chronos::tomorrow();
$meeting = $meeting->addDay(1);
$meeting = $meeting->startOfDay();
 
// Chain the original
// i.e., 2018-05-31 00:00:00.000000
$meeting = \Cake\Chronos\Chronos::tomorrow()
->addDay(1)
->startOfDay();

Immutability makes you enforce intentional changes by explicitly reassigning a date object, and you don’t have to fear passing around the original object.

Learn More

Although the difference feels subtle, using immutable date objects can give you confidence that passing around a date isn’t going to cause a mutation to the original object, unless you explicitly reassign.

I am not trying to say that one style is better than another, I am pointing out that I believe learning about PHP’s DateTimeImmutable can help clarify some of the defensive techniques that immutable dates give your code.

With that in mind, using Carbon, you need to be aware of any dates you intend to pass around to other methods for comparisons or other logic. I would suggest always copying the DateTime instance to avoid mutation, and be aware of potential points of mutability in your dates that could create unexpected results.

If you want to experiment more with an immutable DateTime library with a nice API like Carbon’s, check out the Chronos documentation.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article
Basset is an alternative way to load CSS & JS assets image

Basset is an alternative way to load CSS & JS assets

Read article
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article