Try Augment Code: a power tool for pro Laravel devs

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
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
Lucky Media logo

Lucky Media

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

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

The latest

View all →
Chargebee Starter Kit for Billing in Laravel image

Chargebee Starter Kit for Billing in Laravel

Read article
Streamline Pipeline Cleanup with Laravel's finally Method image

Streamline Pipeline Cleanup with Laravel's finally Method

Read article
Validate Controller Requests with the Laravel Data Package image

Validate Controller Requests with the Laravel Data Package

Read article
Transform JSON into Typed Collections with Laravel's AsCollection::of() image

Transform JSON into Typed Collections with Laravel's AsCollection::of()

Read article
Auto-translate Application Strings with Laratext image

Auto-translate Application Strings with Laratext

Read article