简体   繁体   中英

Calculate days in month with getDate JavaScript

I'm using the following JS to calculate X days ahead of today's date. The output seems to work fine, except the result doesn't consider the days in each month. Therefore, if today is the 26th and I add 9 days, it's outputting the day as the 35th which obviously doesn't make sense.

<script>
  window.onload=function(){
   var dateObj = new Date();

   var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

   var month = months[dateObj.getMonth()]; //months from 1-12
   var day = dateObj.getUTCDate() +9;
   var year = dateObj.getUTCFullYear();

   newdate = day + " " + month + " " + year;
   document.getElementById("date").innerHTML=(newdate);
}
</script>

How can we get it to output the accurate date?

You should be able to do this using the Date.setDate function, instead of getting the day and then adding 9 to it

window.onload = function() {
  var dateObj = new Date();
  // -------------- add this line -------//
  dateObj.setDate(dateObj.getDate() + 9);

  var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  var month = months[dateObj.getMonth()]; //months from 1-12
  var day = dateObj.getUTCDate(); //+9; remove +9
  var year = dateObj.getUTCFullYear();

  newdate = day + " " + month + " " + year;
  document.getElementById("date").innerHTML = (newdate);

}

You should update your date using setDate() using getDate() to get the current date of the month and adding 9.

 window.onload = function() { var dateObj = new Date(); // add 9 days here dateObj.setDate(dateObj.getDate() + 9); var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var month = months[dateObj.getMonth()]; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); newdate = day + " " + month + " " + year; document.getElementById("date").innerHTML = (newdate); } 
 <span id="date"></span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM