Skip to content

Instantly share code, notes, and snippets.

@graste
Created February 2, 2015 10:21
Show Gist options
  • Select an option

  • Save graste/47a4a6433dfe0acf64b7 to your computer and use it in GitHub Desktop.

Select an option

Save graste/47a4a6433dfe0acf64b7 to your computer and use it in GitHub Desktop.
PHP DateTime and DateTimeImmutable

From PHP 5.5 onwards there's DateTimeImmutable which implements the same DateTimeInterface as DateTime and thus should be interchangeable in implementations. The DateTimeImmutable returns new instances with the requested changes when calling modifying functions like modify.

now with microseconds precision instead of seconds

When creating a DateTime instance for the current moment in time (e.g. with the string now) the precision is seconds. Unix timestamp might help. Another option to create a valid NOW value is:

$dti = DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', microtime(true)));

Creation of DateTimeImmutable from a DateTime

From PHP 5.6 onwards there's a static factory method for this. Before this one must use a common ISO8601 format to transfer the value (including sub-second precision):

if (version_compare(PHP_VERSION, '5.6.0') >= 0) {
    $dti = DateTimeImmutable::createFromMutable($datetime);
} else {
    $dti = DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.uP', $datetime->format('Y-m-d\TH:i:s.uP'));
}

Timestamp comparisons

The diff method of DateTime doesn't have sub-second precision. Comparing instances for value equality with sub-second precision must thus be done with something like this:

($dt1 instanceof DateTimeInterface && $dt2 instanceof DateTimeInterface) &&
($dt1 == $dt2) && // no strict comparison as PHP then compares date values instead of instances
((int)$dt1->format('u') === (int)$dt2->format('u')) // compare the microseconds as well m(
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment