使用getDate JavaScript计算每月的天数

时间:2018-07-26 14:34:07

标签: javascript html validation date

我正在使用以下JS来计算今天日期之前的X天。输出似乎工作正常,除非结果不考虑每个月中的天数。因此,如果今天是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>

如何获取准确的日期?

2 个答案:

答案 0 :(得分:3)

您应该可以使用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);

}

答案 1 :(得分:1)

您应该使用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>