Skip to content

EspoCRM – Open Source CRM Application

Fix datetime\diff months sign for backward intervals (#3794)

Leo Camusbd493e843669
diff --git a/application/Espo/Core/Formula/Functions/DatetimeGroup/DiffType.php b/application/Espo/Core/Formula/Functions/DatetimeGroup/DiffType.php
index 244dc2d40a..30e962878e 100644
--- a/application/Espo/Core/Formula/Functions/DatetimeGroup/DiffType.php
+++ b/application/Espo/Core/Formula/Functions/DatetimeGroup/DiffType.php
@@ -129,13 +129,13 @@ class DiffType extends BaseFunction
$interval = $dateTime2->diff($dateTime1);
$number = $interval->$property;
- if ($interval->invert) {
- $number *= -1;
- }
-
if ($intervalType === 'months') {
$number += $interval->y * 12;
}
+
+ if ($interval->invert) {
+ $number *= -1;
+ }
}
return $number;
diff --git a/tests/unit/Espo/Core/Formula/EvaluatorTest.php b/tests/unit/Espo/Core/Formula/EvaluatorTest.php
index b7378b8027..aad2640384 100644
--- a/tests/unit/Espo/Core/Formula/EvaluatorTest.php
+++ b/tests/unit/Espo/Core/Formula/EvaluatorTest.php
@@ -311,6 +311,18 @@ class EvaluatorTest extends TestCase
$this->assertEquals(['1000', '2000'], $actual);
}
+ public function testDatetimeDiffMonths(): void
+ {
+ $expression = "datetime\\diff('2022-03-01', '2020-01-01', 'months')";
+ $this->assertEquals(26, $this->evaluator->process($expression));
+
+ $expression = "datetime\\diff('2020-01-01', '2022-03-01', 'months')";
+ $this->assertEquals(-26, $this->evaluator->process($expression));
+
+ $expression = "datetime\\diff('2020-01-01', '2021-01-01', 'months')";
+ $this->assertEquals(-12, $this->evaluator->process($expression));
+ }
+
public function testStringReplace()
{
$expression = "string\\replace('hello {test} hello', '{test}', 'hello')";