Subject: [PATCH] Fix handling of delta values with negative month field

From: Łukasz Stelmach <[email-masked]>
Date: Wed, 7 Feb 2024 14:37:39 +0100

* lisp/calendar/time-date.el (decoded-time-add): If the new
variable is less then zero, the year needs to be decremented
by quotient of new and 12 increased by one.
* test/lisp/calendar/time-date-tests.el (test-decoded-add):
Add applicable test cases.
---
 lisp/calendar/time-date.el            |  2 +-
 test/lisp/calendar/time-date-tests.el | 12 ++++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/lisp/calendar/time-date.el b/lisp/calendar/time-date.el
index e96e2e7e2db..68b05314f3c 100644
--- a/lisp/calendar/time-date.el
+++ b/lisp/calendar/time-date.el
@@ -473,7 +473,7 @@ decoded-time-add
     (when (decoded-time-month delta)
       (let ((new (+ (1- (decoded-time-month time)) (decoded-time-month delta))))
         (setf (decoded-time-month time) (1+ (mod new 12)))
-        (cl-incf (decoded-time-year time) (/ new 12))))
+        (cl-incf (decoded-time-year time) (- (/ new 12) (if (< new 0) 1 0)))))
 
     ;; Adjust for month length (as described in the doc string).
     (setf (decoded-time-day time)
diff --git a/test/lisp/calendar/time-date-tests.el b/test/lisp/calendar/time-date-tests.el
index 01f9f8a5108..4ca274fcec6 100644
--- a/test/lisp/calendar/time-date-tests.el
+++ b/test/lisp/calendar/time-date-tests.el
@@ -131,6 +131,18 @@ test-decoded-add
     (should (equal (decoded-time-add time (mdec :month 10))
                    '(12 15 16 8 5 2020 1 t 7200)))
 
+    (should (equal (decoded-time-add time (mdec :month -1))
+                   '(12 15 16 8 6 2019 1 t 7200)))
+
+    (should (equal (decoded-time-add time (mdec :month -10))
+                   '(12 15 16 8 9 2018 1 t 7200)))
+
+    (should (equal (decoded-time-add time (mdec :month -14))
+                   '(12 15 16 8 5 2018 1 t 7200)))
+
+    (should (equal (decoded-time-add time (mdec :month -24))
+                   '(12 15 16 8 7 2017 1 t 7200)))
+
     (should (equal (decoded-time-add time (mdec :day 1))
                    '(12 15 16 9 7 2019 1 t 7200)))
 
-- 
2.39.2