Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is getDate() a month off?

I'm trying to iterate over objects that have a date within a specific time frame. These time frames are days in the past week bounded by startDate and endDate.

I have a for loop that sets the startDate to the beginning of the day, and endDate will be the end of the day.

let startDate = new Date(); // startDate: Start bound of average execution time calculation
let endDate = new Date(); // endDate: End bound of average execution time calculation

for (let i = 0; i < 7; i++) {
          // i is used to decrement the startDate to i days from today

          // set startDate to beginning of the day
          startDate = new Date();
          startDate.setDate(startDate.getDate() - i);
          startDate.setHours(0, 0, 0, 0);
          console.log(i + ": " + startDate);

          // set endDate to end of the day
          endDate.setDate(startDate.getDate());
          endDate.setHours(23, 59, 59, 999);
          console.log(i + ": " + endDate);

However, even though I'm setting the endDate to the startDate, the console tells me that the endDate is one month off. Why is this happening?

The console shows this:

0: Sat Aug 01 2020 00:00:00 GMT-0700 (Mountain Standard Time)
0: Sat Aug 01 2020 23:59:59 GMT-0700 (Mountain Standard Time)
1: Fri Jul 31 2020 00:00:00 GMT-0700 (Mountain Standard Time)
1: Mon Aug 31 2020 23:59:59 GMT-0700 (Mountain Standard Time)
2: Thu Jul 30 2020 00:00:00 GMT-0700 (Mountain Standard Time)
2: Sun Aug 30 2020 23:59:59 GMT-0700 (Mountain Standard Time)
3: Wed Jul 29 2020 00:00:00 GMT-0700 (Mountain Standard Time)
3: Sat Aug 29 2020 23:59:59 GMT-0700 (Mountain Standard Time)
4: Tue Jul 28 2020 00:00:00 GMT-0700 (Mountain Standard Time)
4: Fri Aug 28 2020 23:59:59 GMT-0700 (Mountain Standard Time)
5: Mon Jul 27 2020 00:00:00 GMT-0700 (Mountain Standard Time)
5: Thu Aug 27 2020 23:59:59 GMT-0700 (Mountain Standard Time)
like image 245
aztheog Avatar asked Jan 27 '26 00:01

aztheog


1 Answers

Think like arrays, where the first element is 0. The same is true here. The months of the year will be 0 - 11, rather than 1 - 12. The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).

Also, keep this in mind: With setDate() the expected values are 1-31, but other values are allowed: 0 will result in the last day of the previous month. -1 will result in the day before the last day of the previous month.

like image 97
Muirik Avatar answered Jan 28 '26 13:01

Muirik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!