Skip to content

Commit c9bf6d8

Browse files
fix(calendar): Properly go to previous/next year
1 parent 8e319bf commit c9bf6d8

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

lua/orgmode/objects/date.lua

+20-3
Original file line numberDiff line numberDiff line change
@@ -537,11 +537,28 @@ end
537537
---@return number
538538
function Date._days_of_month(date)
539539
local days_of = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
540-
if date.month == 2 then
540+
local month = date.month
541+
542+
if month == 2 then
541543
return Date._days_of_february(date.year)
542-
else
543-
return days_of[date.month]
544544
end
545+
546+
if month >= 1 and month <= 12 then
547+
return days_of[month]
548+
end
549+
550+
-- In case the month goes below or above the threshold (via adding or subtracting)
551+
-- We need to adjust it to be within the range of 1-12
552+
-- by either adding or subtracting
553+
if month < 1 then
554+
month = 12 - month
555+
end
556+
557+
if month > 12 then
558+
month = month - 12
559+
end
560+
561+
return days_of[month]
545562
end
546563

547564
function Date._days_of_february(year)

tests/plenary/object/date_spec.lua

+8
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,14 @@ describe('Date object', function()
329329
assert.are.same('2020-03-26 Thu 12:30', date:to_string())
330330
end)
331331

332+
it('properly adds and subtracts month at the edge of the year', function()
333+
local date = Date.from_string('2024-01-03 Wed 14:00')
334+
date = date:subtract({ month = 1 })
335+
assert.are.same('2023-12-03 Sun 14:00', date:to_string())
336+
date = date:add({ month = 1 })
337+
assert.are.same('2024-01-03 Wed 14:00', date:to_string())
338+
end)
339+
332340
it('should compare dates', function()
333341
local date = Date.from_string('2021-05-12 14:00')
334342
local date_end = Date.from_string('2021-05-12 23:30')

0 commit comments

Comments
 (0)