4

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?

kboul
  • 13,836
  • 5
  • 42
  • 53
  • Set the date with `setUTCDate()` to the current value plus your offset, and then get the day of month back after that. It'll also update the month value, so do that before you get the month and year too. – Pointy Jul 26 '18 at 14:35
  • @Pointy Can you show me in code please? I'm not too good at JS myself, I modified this code from somewhere else. Thank you :) – user3827625 Jul 26 '18 at 14:37
  • This should be closed, there are already [*many answers*](https://stackoverflow.com/search?q=%5Bjavascript%5D+add+days+to+a+date), e.g. [*How can I add 1 day to current date?*](https://stackoverflow.com/questions/9989382/how-can-i-add-1-day-to-current-date/9989458#9989458) – RobG Jul 27 '18 at 00:25

2 Answers2

3

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

}
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

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>
phuzi
  • 12,078
  • 3
  • 26
  • 50