Skip to content

Commit

Permalink
fix(getPrevDate): the wrong result was sometimes returned for months …
Browse files Browse the repository at this point in the history
…with less than 31 days

Closes #313

Signed-off-by: Pascal Sthamer <10992664+P4sca1@users.noreply.github.com>
  • Loading branch information
P4sca1 committed Apr 29, 2024
1 parent c14e569 commit 6537bc1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ export class Cron {
}

// We try every month within the past 5 years to make sure that we tried to
// find a matching date insidde a whole leap year.
// find a matching date inside a whole leap year.
const maxIterations = this.reversed.months.length * 5

for (let i = 0; i < maxIterations; i++) {
Expand All @@ -444,7 +444,10 @@ export class Cron {
'prev',
year,
month,
isStartMonth ? startDateElements.day : 31,
isStartMonth
? startDateElements.day
: // Start searching from the last day of the month.
getDaysInMonth(year, month),
)
let isStartDay = isStartMonth && day === startDateElements.day

Expand Down
10 changes: 10 additions & 0 deletions test/cron.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,16 @@ describe('getPrevDate(s)', () => {
new Date(2020, 9, 5, 18, 50, 2),
),
).toStrictEqual(new Date(2019, 11, 31, 0, 0, 0))

// https://github.com/P4sca1/cron-schedule/issues/313
// Cron: every Wednesday at 10:00
// Start date: 01.05.2025 10:00:00
// Expected: 24.04.2024 10:00:00
expect(
parseCronExpression('0 10 * * 3').getPrevDate(
new Date(2024, 4, 1, 9, 0, 0),
),
).toStrictEqual(new Date(2024, 3, 24, 10, 0, 0))
})

test('Should correctly get the previous dates', () => {
Expand Down

0 comments on commit 6537bc1

Please sign in to comment.