[英]Calculate days in month with getDate JavaScript
I'm using the following JS to calculate X days ahead of today's date. 我正在使用以下JS来计算今天日期之前的X天。 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.
因此,如果今天是第26天并且我增加了9天,它将输出当天作为第35天显然没有意义。
<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 您应该能够使用Date.setDate函数执行此操作,而不是获取日期,然后向其中添加9
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()
更新日期,以获取当月的当前日期并添加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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.