• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Draft / PHP Convert to DateTimeImmutable

PHP Convert to DateTimeImmutable

Last updated on February 25, 2019 by Sal Ferrarello

In PHP 5.5 the DateTimeImmutable class was introduced. Immutable objects are nice in that they can not be modified, which helps reduce the likelihood I make certain types of errors.

Type Hinting DateTime

When using type declarations (a.k.a. type hinting), you can use the DateTimeInterface, which accepts either a DateTime or a DateTimeImmutable object. This is great but it means I may now have a mutable DateTime object (instead of a DateTimeImmutable object).

Convert to DateTimeImmutable

The DateTimeImmutable class comes with a helper static function createFromMutable(), which takes a DateTime object and returns a DateTimeImmutable object. Unfortunately, DateTimeImmutable::createFromMutable() throws an error if you use a DateTime object as the parameter, therefore we need to do a check before calling this function.

This is the code I use to ensure my value is an instance of DateTimeImmutable.

function myFunction(DateTimeInterface $dt) {
    $dt = $dt instanceof DateTimeImmutable ?
          $dt :
          DateTimeImmutable::createFromMutable($dt);
    // Now $dt is definitely a DateTimeImmutable object.

    // Other code goes here.
}
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Draft, Programming Tagged With: DateTime, PHP

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in