I am trying to understand the logic to rollback the date to previous month.
const now = new Date();
console.log(`Initial Date: ${now}`); // Initial Date: Wed Oct 23 2024 00:01:56 GMT-0500 (CST)
now.setDate(-1);
console.log(`Updated Date: ${now}`); // Updated Date: Sun Sep 29 2024 00:01:56 GMT-0500 (CST)
Here, why the Updated Date
in not showing as Sep 30
?
I am unable to understand the output Updated Date: Sun Sep 29 2024 00:01:56 GMT-0500 (CST)
3
Answers
When you use now.setDate(-1), you’re not actually rolling back the date to the previous month. Instead, you’re setting the date to the 1st day of the current month minus 1 day.
Here’s how it works:
to set the date to the 1st of October (because the Date object
rolls back to the start of the month) and then subtract 1 day,
which results in September 29, 2024.
Use this to get the
Explanation:
previous month.
The behavior you are encountering is due to how JavaScript’s Date object handles negative values for dates. Let’s break it down step-by-step.
Why now.setDate(-1) results in Sep 29 instead of Sep 30
1.Understanding setDate() behavior:
When you pass 0 to setDate(), it sets the date to the last day of the previous month.
If you pass a negative value, JavaScript rolls back into the previous month, counting backwards from the last day.
2.In your case:
The initial date is Oct 23, 2024.
When you call now.setDate(-1), it doesn’t just jump to the last day of the previous month (Sep 30). Instead:
Date -1 means one day before Sep 1.
So, it keeps rolling backwards to the end of the previous month: August 31, and subtracts 1 more day to land on Sep 29.
3.Expected Output with setDate(0): If you want to get Sep 30 (the last day of September), use:
setDate(0) will take the date back to Sep 30 (since 2024 is a leap year and September has 30 days).
Key Takeaways:
setDate(-1) rolls back across months in an unexpected way because it counts backwards continuously from the current month into previous months.
Use setDate(0) if you want the last day of the previous month.
This behavior is a quirk of JavaScript’s Date object when handling negative values for dates.
You can find an answer in the official documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
dates, rather than actual day you want to subtract or add
[29 sept, 30 sept, 1 oct, …. 30 oct, 31 oct, 1 nov]
[-1,0,1,…30,31, 32]
setting date to 0 will always point you to the last day of the previous month:
So in your example setting it to -1 will return 29th of September.