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
Laravel Cloud

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

Visit Laravel Cloud
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Shift logo

Shift

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

Shift
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
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 $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises

The latest

View all →
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article
Laravel LSP: A First-Party Language Server Announced at Laracon US 2026 image

Laravel LSP: A First-Party Language Server Announced at Laracon US 2026

Read article
Watch Laracon US 2026 Live on YouTube image

Watch Laracon US 2026 Live on YouTube

Read article
Monthly Log Driver in Laravel 13.23 image

Monthly Log Driver in Laravel 13.23

Read article
Pinion UI: Restyle an Entire Laravel App by Changing Two HTML Attributes image

Pinion UI: Restyle an Entire Laravel App by Changing Two HTML Attributes

Read article
Building a Live Match Scoreboard With Laravel Reverb image

Building a Live Match Scoreboard With Laravel Reverb

Read article