Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated.

I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month:

private _getDaysOfMonth(year: number, month: number): Array<Date> {
    const date = new Date(year, month, 1)

    const days = []
    while (date.getMonth() === month) {
        days.push(date) 
        console.log(date) // The output seems correct, for example: Fri Jan 01 2021 00:00:00 GMT+0300 (Moscow Standard Time)
        date.setDate( date.getDate() + 1 )
    }
   
    console.log(days) // I anticipated an array of days from January 1 to January 31, 2021, but instead, I see February
    return days
}

When calling the method with parameters 2021 and 0

this._getDaysOfMonth(this._year, this._month)

I am expecting an array of days in January, however, I am getting an array of days in February!

This is what my console.log displays: console.log

Answer №1

Utilizing new Date() to create a fresh date instance each time an item is added:

function fetchDaysOfMonth (year, month) {
  const currentDate = new Date(year, month)

  const daysArray = []
  while (currentDate.getMonth() === month) {
    daysArray.push(new Date(currentDate)) // Using new Date() for creating new date instances
    console.log(currentDate)
    currentDate.setDate(currentDate.getDate() + 1)
  }

  console.log(daysArray)
  return daysArray
}

fetchDaysOfMonth(2021, 1)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automating the scrolling function in Angular 2 to automatically navigate to the bottom of the page whenever a message is sent or opened

In my message conversation section, I want to ensure that the scroll is always at the bottom. When the page is reopened, the last message should be displayed first. HTML: <ul> <li *ngFor="let reply of message_show.messages"> ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

When using ESLint together with React, you may encounter errors related to `no-unused-vars

I've configured eslint and eslint-plugin-react. After running ESLint, I'm encountering no-unused-vars errors for all React components. It seems that the linter is not recognizing JSX or React syntax. Any solutions? For example: app.js import ...

Ways to calculate specific hours within a date range?

Is there a way to calculate the difference between dt1 and dt2 while considering only 7 hours from each day? from datetime import datetime def get_total_hours(): dt1 = some_datetime # datetime.datetime(2022, 7, 25, 18, 4, 4, 204105) dt2 = ...

The backend is not receiving the AJAX post, which utilizes dynamically-generated JSON

I'm relatively new to Bootstrap and frontend development in general. On a page I'm working on, there's a table that displays various configurations to the user. Each row has a Change button that triggers a modal popup when clicked. Here&apos ...

Unable to update state from within a function in react

As I delve into the realm of coding, a simple graph catches my eye. It showcases various data sets including current, all, and filtered data. Initially, the first block of code runs smoothly. However, upon attempting to setState in order to make some modif ...

Guide on adding the contents of non-empty <td> tags using Javascript or JQuery

My goal is to calculate the total sum of all the HTML content within <td> elements with the attribute name='gross_val'. Here are the <td> elements I am working with: <tr><td name="gross_val" align="right" title="gross_val1" ...

The method by which JavaScript identifies when a Promise has resolved or rejected

How does JavaScript determine when the state of myPromise has transitioned to "fulfilled" in the code provided below? In other words, what is the process that determines it's time to add the .then() handler to the microqueue for eventual execution? co ...

Adjust form elements dynamically depending on the selected option in a dropdown menu using Ruby on Rails

I currently have the following database tables set up: Departments ID| Department_name | Manager_ID Employees ID| Name | Department_ID Salaries ID| Employee_ID | Salary_Amount The departments table holds information about different departments within t ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

Achieve maximum height with background images

Having trouble with responsiveness on my box containing a background image. I am aiming for the box to adjust its height based on the background image, as I have set the background-size attribute to auto. html: <div class="index_boxs" id="discover_win ...

I am facing an issue in my Nextjs project where the Array Object is not being properly displayed

Hi there! I am new to Nextjs and currently learning. I recently created a component called TeamCard which takes imgSrc, altText, title, designation, and socialProfile as parameters. However, when attempting to display the socialProfile object array using m ...

Adjust input width based on content in VueJS

Is it possible to achieve the following using (Pug & CoffeeScript): input(placeholder="0", v-model.number="order[index]" v-on:change="adjustInput") ... adjustInput: -> event.target.style.width = event.target.value.length + 'ch' Even ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Retrieving Dropdown Values based on Selection in Another Dropdown

On my website, there are two dropdown lists available: 1) One containing Book Names 2) The other containing Links to the Books. All data is stored in an XML file structured like this: <?xml version="1.0" encoding="UTF-8"?> <BookDetail> <boo ...

Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules. For example, if we have a component using regular css: import React from 'react' import ". ...

Invoke custom_function on every individual element in the array

I have an array with a list of IDs [1,2,3,4,5]; and I want to apply the function custom_function to each element. Once all instances of the custom_function have completed their work, I want to get the result of the function. How can I achieve this using ...

Developing pagination functionality in ReactJS

I came across this piece of code in a forum (how to implement Pagination in reactJs): constructor() { super(); this.state = { todos: ['a','b','c','d','e','f','g','h ...

Experiencing a lack of content in an Express response

Currently utilizing express to manage a POST request, but encountering an issue when sending the body using node-fetch. After sending the body and logging it in express (server-side code), I am seeing an empty object. The reason behind this behavior remain ...

When attempting to open an Angular modal window that contains a Radio Button group, an error may occur with the message "ExpressionChanged

I am brand new to Angular and have been trying to grasp the concept of lifecycle hooks, but it seems like I'm missing something. In my current project, there is a Radio Button Group nested inside a modal window. This modal is triggered by a button cl ...