note 114826 added to class.dateinterval
| From: | 0bccbf3a at opayq dot com | Date: | Thu, 10 Apr 2014 17:26:39 +0000 |
| Subject: | note 114826 added to class.dateinterval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-199241@lists.php.net to get a copy of this message | ||
invert flag is unreliable.
If you've created interval with \DateInterval::createFromDateString with value like '1 day
ago' than actually days counter will be negative, and invert flag will be 0. Also, setting
invert to 1 with negative units is not working.
Reliable solution to check if interval is negative is to actually apply it and compare:
<?php
private function isNegative(\DateInterval $interval)
{
$now = new \DateTimeImmutable();
$newTime = $now->add($interval);
return $newTime < $now;
}
?>
Also, if you want to compare some units of two intervals you should take abs() of them. Or make
whole interval absolute:
<?php
private function absInterval(\DateInterval $interval)
{
$now = new \DateTimeImmutable();
$new = $now->add($interval);
$newInt = $now->diff($new);
if (1 === $newInt->invert) {
$newInt->invert = 0;
}
return $newInt;
}
?>
P.S.: tested on 5.5.12-dev and 5.5.9
----
Server IP: 72.52.91.14
Probable Submitter: 109.188.125.156
----
Manual Page -- http://php.net/manual/en/class.dateinterval.php
Edit -- https://master.php.net/note/edit/114826
Del: integrated -- https://master.php.net/note/delete/114826/integrated
Del: useless -- https://master.php.net/note/delete/114826/useless
Del: bad code -- https://master.php.net/note/delete/114826/bad+code
Del: spam -- https://master.php.net/note/delete/114826/spam
Del: non-english -- https://master.php.net/note/delete/114826/non-english
Del: in docs -- https://master.php.net/note/delete/114826/in+docs
Del: other reasons-- https://master.php.net/note/delete/114826
Reject -- https://master.php.net/note/reject/114826
Search -- https://master.php.net/manage/user-notes.php