What is the reason behind the inconsistent behavior of Javascript's Date.getDate() and .setDate() methods?

As a hobbyist coder, I'm facing a challenging problem with building a dynamic HTML/CSS calendar. My goal is to have cells filled in based on today's date. However, when I attempt to add days to fill in another 13 days by looping through HTML elements.innerHTML, I hit a roadblock.

If I use setDate(30 + 2) and then getDate(), everything works perfectly fine. Javascript recognizes that June ends on the 30th day, resulting in 2 (July 2nd), just as I wanted.

Here lies the issue - this method only functions properly if there is a single call. When I introduce a loop or make multiple calls to this code, the outcome varies. Could it be some asynchronous operation causing this inconsistency? Below is the code snippet:

const theDate = new Date();
    const todaysDate = 30;
    
    theDate.setDate(todaysDate + 1);
    let result1 = theDate.getDate();
    
    theDate.setDate(todaysDate + 2);
    let result2 = theDate.getDate();
    
    theDate.setDate(todaysDate + 3);
    let result3 = theDate.getDate();
    
    theDate.setDate(todaysDate + 4);
    let result4 = theDate.getDate();
    
    console.log(result1);
    console.log(result2);
    console.log(result3);
    console.log(result4);

Answer №1

June may have 30 days, but July boasts 31.

Should you dare to set the date to 32 for the very first time, it lands on the non-existent 32nd of June - subsequently rolling over to July 2nd due to its proximity to the end of June. (32-30=2)

Attempting to set the date to 32 once more finds us in July already, causing the extra days beyond July 31 to carry us into August 1st. (32-31=1).

Answer №2

Regarding your inquiry, the behavior of the setDate() function may appear strange to you due to setting the date relative to the previous value. This results in increments of 31, 32, or 33 days instead of by 1, 2, or 3. For more detailed insight, refer to @Quentin's insightful response. I simply wanted to highlight the root cause and provide my own solution.


If you seek an alternative approach for generating dates:

const dayOfMonth = 30;
const date = new Date();
date.setDate(dayOfMonth);
console.log("Date:", date);

let timestamp = Date.parse(date);

for (let i = 1; i <= 14; i++) {
  const newTimestamp = timestamp + i * (1000 * 60 * 60 * 24);
  const newDate = new Date(newTimestamp);
  console.log("New date:", newDate);
}

This method involves manipulating the timestamp to generate new dates based on the incremental addition of milliseconds in a day.

You can customize your date logic within the loop to populate the calendar as mentioned.

Answer №3

If you implement the Date() constructor in each loop, there is no need to be concerned about the varying days in a specific month.

Detailed explanations are included in the example below

/**
 * @desc - generate a sequence of dates beginning from today (or a specified
 *         date) and extending for a given number of days
 * @param {number} range - The number of days
 * @param {string<date>} start - The starting date for the sequence,
 *        default is today if not specified
* @return {array<date>} An array containing the generated dates
 */
function dayRange(range, start) {
  // Use today's date as default if 'start' is undefined
  let now = start ? new Date(start) : new Date();
  // Create an array of empty slots with length equal to 'range'
  let rng = [...new Array(range)];

  /*
  Iterate through the 'rng' array
  Add today's date in the first iteration... 
  ... then calculate tomorrow's date for subsequent iterations...
  ... and return it in local format
  */
  return rng.map((_, i) => {
    if (i === 0) {
      return now.toLocaleDateString();
    }
    let day = now.getDate() + 1;
    now.setDate(day);
    return now.toLocaleDateString();
  });
}

console.log("Specify the first parameter if today is the starting point");
console.log(JSON.stringify(dayRange(14)));

console.log("Provide a properly formatted date string as the second parameter to start on a date other than today");
console.log(JSON.stringify(dayRange(10, '05/12/2020')));

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

Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt. My approach involves using JavaScript and vue.js. Function responsible fo ...

Using Twig path to pass Ajax URL parameter

I'm facing an issue in my Twig view when passing parameters in the AJAX URL path. Since Twig is executed before JavaScript, it doesn't recognize the input value passed as a parameter. Is there a way to solve this without passing the param in data ...

Setting the CSS property `overflow-y: scroll;` does not make the element scrollable and causes it to exceed 100% of the block

I am seeking a solution to create a y-axis scrollable block within the left-navbar. The height of this block should occupy all available space within the left-navbar, ensuring that the left-navbar itself remains at 100% of the page height. The issue arise ...

Mapping the Way: Innovative Controls for Navigation

Currently, I am utilizing the HERE maps API for JavaScript. However, I would like to customize the design of the map controls similar to this: Below is an example for reference: HERE EXAMPLE Is it feasible to achieve this customization? ...

Angular allows for dynamic sourcing of iframes

I have encountered an issue while trying to integrate a payment system with Angular. The payment gateway API I am using provides the 3D Secure Page as html within a JSON response. My approach is to display this html content within an iframe, however, the h ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

Using Jquery to make an Ajax request to a PHP script that retrieves JSON data

Hello, I am new to working with JSON. I have a PHP script that contains a multidimensional array, which is then encoded into JSON format like this: <?php header('Content-Type: application/json'); $lista = array ( 'Conoscenti'=&g ...

Which is better: triggering mouseleave from inside or outside of mouseenter event

As I delve into the basics of jQuery, I stumbled upon mouseenter and mouseleave actions. The question that arose in my mind is: where should I place the mouseleave action? Which approach is more correct and reliable? $(document).ready(function(){ $(&a ...

Where is the best location to store the image files?

I am currently working on a web application that focuses on Image processing, however I have encountered a basic issue. The images are not loading during the runtime of my HTML page. I have tried placing the image files in the src folder, but it seems li ...

Click the button to send the form without including any hidden HTML element array value

My main goal is to create a dynamic dropdown menu for users when they click a button. Each click triggers a new dropdown to appear. To achieve this, I have been cloning a hidden div each time the button is clicked. Here's an example of how I am accom ...

How can you use React.js to only display "Loading..." on the page while the full name is included in the URL?

I've hit a roadblock while trying to solve this issue. Here's the situation: On the page where I need to display certain information, I intended to showcase the full name of the individual from a previous form submission. However, instead of seei ...

Using webGL for rendering drawElements

I am working with face-indices that point to specific points to draw triangles in a loop. Unfortunately, when executing my code, I encountered the following error in the web console: WebGL: drawElements: bound element array buffer is too small for given c ...

Using orchestrate.js for local passport.js authentication

I need assistance finding a tutorial or resources for setting up local passport.js authentication with Orchestrate as the user storage. Most of the resources I have come across are based on MongoDB, but our project requires us to use Orchestrate. Any advic ...

Feeling puzzled by the concept of CSS Block Formatting Contexts (BFCs)

In the World Wide Web Consortium (W3C), the concept of Block Formatting Context (BFC) is explained as follows: Within a block formatting context, boxes are arranged one after another in a vertical manner, starting at the top of a containing block. The dist ...

Enable tabber upon clicking on the navigation bar

Hello there, I am facing an issue with my website's navigation. I have a navigation bar with the unique id #nav and I want to activate a specific tab based on the clicked navigation list item. The HTML structure of the navigation #nav looks like this: ...

Updating and removing items from a React state using push and pop methods

I am working on a component in React and have the following state: this.state = { Preferences: [] } I am trying to push an element only if it does not already exist in the array to avoid adding duplicate elements. If the element is already ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Incorporate content from a single HTML file into a different one

Hello, I am working with two HTML documents - let's call them index.html and index2.html for this example. I am looking to embed all the code within the body tag of index2.html into a section within index.html. Is there a way to create this connectio ...

Why are imported modules unable to reach global variables in Node?

As I delve deeper into using ES6 and organizing my code across multiple files for better readability and version control, I've encountered an issue that has me puzzled. In one of my scenarios, I have a class defined in a separate file called class.js, ...