Calculate days in month with getDate Javacript

Clash Royale CLAN TAG#URR8PPPCalculate days in month with getDate Javacript
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?
setUTCDate()
@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
9 hours ago
This should be closed, there are already many answers, e.g. How can I add 1 day to current date?
– RobG
7 mins ago
2 Answers
2
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.
setDate()
getDate()
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>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
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
9 hours ago