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)
1
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:
- Initial Date: Let’s say today is October 23, 2024.
- Setting the Date: When you call now.setDate(-1), you’re telling it
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
const now = new Date();
const lastDayOfPreviousMonth = new Date(now.getFullYear(), now.getMonth(), 0);
console.log(`Last Day of Previous Month: ${lastDayOfPreviousMonth}`);
Explanation:
- new Date(year, monthIndex, day): This constructor creates a new date.
- The monthIndex is zero-based (0 for January, 1 for February, etc.).
- now.getFullYear(): Gets the current year. now.getMonth() – 1: Gets he
previous month.
1
You can find an answer in the official documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
The setDate() method of Date instances changes the day of the month
for this date according to local time.
- setDate() function does not execute relative calculation to the date stored in variable. But rather sets the actual date based on value providedl
- Treat the value of setDate() function as index of an array with
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:
const date = new Date();
// 23 oct
console.log(date.toDateString());
date.setDate(0);
// 30 sep
console.log(date.toDateString());
// important!: you have changed the month to september with setDate(0)
//so you will be looking up for an array of dates in september now
date.setDate(1);
// 1 sep
console.log(date.toDateString());
So in your example setting it to -1 will return 29th of September.