Skip to Content
Course content

95: The DateTime and DateTimeImmutable Classes

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you have a whiteboard in your office with a project deadline written on it: October 1st. If you walk up to that board, erase "October 1st," and write "October 15th," the original date is gone. Anyone who walks into the room now only sees the 15th. That's a mutable state.

Now, imagine instead that you take a photograph of that whiteboard. If you open that photo in an editing app and change the date to October 15th, you've created a new image. The original photo—and the actual whiteboard in your office—remain exactly as they were. That is immutability.

In PHP, DateTime is your whiteboard. DateTimeImmutable is your photo. Let's map that to how the code actually behaves.

The Danger of the Shifting Date

For a long time, DateTime was the only game in town. It's powerful, but it has a nasty habit: it modifies the object itself. I've seen countless bugs where a developer tried to calculate a future date, but accidentally changed the original "start date" in the process.

$startDate = new DateTime('2023-01-01');
$expiryDate = $startDate->modify('+30 days');

echo $expiryDate->format('Y-m-d'); // 2023-01-31
echo $startDate->format('Y-m-d'); // 2023-01-31 (Wait, what?!)

Notice what happened there. Because modify() changes the object it's called on, $startDate and $expiryDate are actually pointing to the exact same object. You didn't create a second date; you just moved the first one forward and gave it a second name. In a large application, this is a recipe for disaster.

Safety First with Immutability

This is why you should almost always reach for DateTimeImmutable. It behaves exactly like DateTime, but with one crucial difference: any method that would change the date instead returns a brand new object.

$startDate = new DateTimeImmutable('2023-01-01');
$expiryDate = $startDate->modify('+30 days');

echo $expiryDate->format('Y-m-d'); // 2023-01-31
echo $startDate->format('Y-m-d'); // 2023-01-01 (Safe!)

See the difference? $startDate stayed put. This makes your code predictable. You can pass an immutable date object into five different functions, and you can be 100% certain that none of those functions will accidentally shift your date to next year.

Moving Through Time

Whether you use the mutable or immutable version, you have a few primary ways to manipulate time. While modify() is great for human-readable strings (like "+1 week" or "next Tuesday"), you'll often want more precision using DateInterval.

I prefer add() and sub() when I'm dealing with specific intervals. It feels more explicit.

$date = new DateTimeImmutable('2023-01-01');

// Create an interval: P (Period) 1M (1 Month)
$interval = new DateInterval('P1M'); 

$nextMonth = $date->add($interval);
$lastMonth = $date->sub($interval);

One quick tip: if you're working with a legacy codebase and you're stuck with a DateTime object but you want the safety of immutability, you can convert it using DateTime::createFromMutable(). It's a lifesaver when you're refactoring old code without wanting to break every single function call in the system.




📋 Practical Task

Subscription Renewal Sequence Generator

You are building a billing system. You need to generate a list of the next three renewal dates for a customer, based on their initial sign-up date. However, you must ensure the original sign-up date remains unchanged so it can be used for the customer's profile page.

Requirements:

  • Create a DateTimeImmutable object representing a sign-up date of 2024-05-10.
  • Using a loop or individual calls, calculate the renewal dates for the 1st, 2nd, and 3rd months following the sign-up.
  • Print each renewal date in the format Y-m-d.
  • At the very end, print the original sign-up date to prove that it was not modified during the calculations.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.