user3827625
user3827625

Reputation: 41

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?

Upvotes: 4

Views: 121

Answers (2)

ControlAltDel
ControlAltDel

Reputation: 35096

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);

}

Upvotes: 3

phuzi
phuzi

Reputation: 13059

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>

Upvotes: 1

Related Questions