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.
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)));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'));
}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(