Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-cron-next-missing-day-overflow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

Fix `Cron.next` skipping earlier matching days when the upcoming day-of-month does not exist in the current month. For an expression like `0 0 1,16,31 * *`, advancing from a date past the 16th selected day 31; in a month without 31 days this overflowed into the following month and landed on a later matching day (e.g. the 16th), silently skipping the 1st. `Cron.next` now wraps to the first matching day of the next month in that case, matching the behaviour of `Cron.prev` and other cron implementations.
6 changes: 6 additions & 0 deletions packages/effect/src/Cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,12 @@ const stepCron = (cron: Cron, startFrom: DateTime.DateTime.Input | undefined, di
} else {
b = daysInMonth(current) - currentDay + boundary.day
}
} else if (!prev && nextDay > daysInMonth(current)) {
// The next matching day does not exist in the current month (e.g. day 31
// in a 30-day month). Setting it directly would overflow into the following
// month and skip its earlier matching days, so wrap to the first matching
// day of the next month instead.
b = daysInMonth(current) - currentDay + boundary.day
} else {
b = nextDay - currentDay
}
Expand Down
15 changes: 15 additions & 0 deletions packages/effect/test/Cron.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,21 @@ describe("Cron", () => {
deepStrictEqual(prev(cron, from), new Date("2024-01-31T00:00:00.000Z"))
})

it("next does not skip earlier days when the upcoming day is missing from the month", () => {
const tz = DateTime.zoneUnsafeMakeNamed("UTC")
const cron = Cron.unsafeParse("0 0 1,16,31 * *", tz)
// From Feb 18 the next matching day in February would be the 31st, which does
// not exist. Rolling onto it must not overshoot past March 1 (also a match).
deepStrictEqual(next(cron, new Date("2020-02-18T00:00:00.000Z")), new Date("2020-03-01T00:00:00.000Z"))
// `*/15` expands to days [1, 16, 31] and exhibits the same wrap.
deepStrictEqual(
next(Cron.unsafeParse("0 0 */15 * *", tz), new Date("2020-02-18T00:00:00.000Z")),
new Date("2020-03-01T00:00:00.000Z")
)
// 30-day month: from the 20th the next day is the 31st (missing) → July 1.
deepStrictEqual(next(cron, new Date("2024-06-20T00:00:00.000Z")), new Date("2024-07-01T00:00:00.000Z"))
})

it("prev clamps to the last valid day when rolling back a month with only month constraints", () => {
const tz = DateTime.zoneUnsafeMakeNamed("UTC")
const cron = Cron.unsafeParse("0 0 0 * FEB *", tz)
Expand Down
Loading