skip to Main Content

I need to visualize a div containing all 30 days after the current one. But when javascript add a day after 1 december 2024 the result is 1 january 2025.

This is the code

var ldate = new Date();
var shdate = new Date(); 
    
function updCalen(){
  document.getElementById('settim').innerHTML = ""
  var vday  = 0 ;
  for (i= 0; i < 30; i++) {
    shdate.setDate(ldate.getDate() +  i );
    document.getElementById('settim').innerHTML += shdate + '<BR>' ;        
  }
}
    
updCalen()
<div id="settim" style="width:600px; height:400px; padding:3px; border: #099 thin solid; overflow:scroll"></div>

I’m struggling with this problem but I can’t find how to solve it!

2

Answers


  1. function updCalen(date, days) {
      const result = new Date(date);
      result.setDate(result.getDate() + days);
      return result;
    }
    
    var today = new Date();
    for (i = 0; i < 30; i++) {
      const newDate = updCalen(today, i);
    }
    
    Login or Signup to reply.
  2. Your problem is with using get/setDate, which sets the day of the month. A better way to solve this problem is to use get/setTime

    document.querySelector('input').valueAsDate = new Date();
    document.querySelector("button").addEventListener( "click", () => {
      let dt = new Date(document.querySelector("Input").value);
      console.log(dt);
      let time = dt.getTime();
      time = time + 30 * 24 /*hours*/ * 60 /* minutes */ * 60 /* seconds */ * 1000 /* ms */
      let newDt = new Date(time);
      console.log(newDt);
    });
    <input type="date" />
    <button>Test</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search