From 8b4efeeb114947fba899f0555694035c1916d18c Mon Sep 17 00:00:00 2001 From: kolaente Date: Wed, 1 Sep 2021 22:12:46 +0200 Subject: [PATCH] Another day, another js date edge-case --- src/helpers/time/parseDate.ts | 11 ++++++++++- src/modules/parseTaskText.test.js | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/helpers/time/parseDate.ts b/src/helpers/time/parseDate.ts index 762f9f72..09e072f0 100644 --- a/src/helpers/time/parseDate.ts +++ b/src/helpers/time/parseDate.ts @@ -291,7 +291,16 @@ const getDayFromText = (text: string) => { } const date = new Date() - date.setDate(parseInt(results[0])) + const day = parseInt(results[0]) + date.setDate(day) + + // If the parsed day is the 31st but the next month only has 30 days, setting the day to 31 will "overflow" the + // date to the next month, but the first. + // This would look like a very weired bug. Now, to prevent that, we check if the day is the same as parsed after + // setting it for the first time and set it again if it isn't - that would mean the month overflowed. + if(day === 31 && date.getDate() !== day) { + date.setDate(day) + } if (date < new Date()) { date.setMonth(date.getMonth() + 1) diff --git a/src/modules/parseTaskText.test.js b/src/modules/parseTaskText.test.js index 390b81d2..b9cdfbe5 100644 --- a/src/modules/parseTaskText.test.js +++ b/src/modules/parseTaskText.test.js @@ -185,7 +185,7 @@ describe('Parse Task Text', () => { expect(result.text).toBe('Lorem Ipsum') expect(result.date.getDate()).toBe(date.getDate()) - expect(result.date.getMonth()).toBe(date.getMonth() + 1) + expect(result.date.getMonth()).toBe(result.date.getDate() === 31 ? date.getMonth() + 2 : date.getMonth() + 1) }) it('should recognize dates of the month in the future', () => { const nextDay = new Date(+new Date() + 60 * 60 * 24 * 1000)