Bradford1802
Bradford180215mo ago

Dates don't increment correctly

when I run the below function with the specific date 2023-09-30, I get the result of n-1 (for any number > 0), where n is the number of the increment specified. It is only this specific date that appears to have this issue, if I change the Year, Month and/or Day it works. function addDay(date, days) { const newDate = new Date(date); newDate.setDate(newDate.getDate() + days); return newDate.toISOString().substring(0,10); }; console.log(addDay("2023-09-30", 1));
2 Replies
pyrote
pyrote15mo ago
It could be because of the local system's time zone. newDate.getDate() will return the date based on the local time. Which can be one day less than the UTC date depending on the time of day. You could use newDate.getUTCDate() if you want to keep everything in UTC.
Bradford1802
Bradford180215mo ago
put a work around in place and it works. Strangely this only occurs for dates in Sep and Oct for years between 1994 - 2024. function addDay(date, days) { const newDate = new Date(date) newDate.setDate(newDate.getDate() + days) const checkDate = newDate.toISOString().substring(0, 10) if (checkDate === date) { newDate.setDate(newDate.getDate() + days + 1) return newDate.toISOString().substring(0, 10) } else { return newDate.toISOString().substring(0, 10) } }