如何显示从当前日期开始的未来3个月

时间:2019-11-28 06:09:33

标签: jquery

$(document).ready(function(){
        var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var month = (new Date()).getMonth();
        for (; month < monthNames.length; month++) {
        $('select').append('<option>' + monthNames[month] + '</option>');
        }
    });

如何使用jquery将当前日期后的3个月显示为下拉列表,当当前月或下个月完成时,我需要将相应的未来3个月显示为下拉列表。

2 个答案:

答案 0 :(得分:1)

您的代码非常接近,您只需要添加一个计数器,以便仅输出3个值,并且在递增month时,您需要使用模算术,以便在到达十二月:

$(document).ready(function() {
  var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var month = ((new Date()).getMonth()+1)%12;
  for (i = 0; i < 3; i++, month = (month + 1) % 12) {
    $('select').append('<option>' + monthNames[month] + '</option>');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>

答案 1 :(得分:0)

使用toLocaleDateString()

var date = new Date()
for (var i = 0; i < 3; i++) {
  date.setMonth(date.getMonth() + 1, 1)
  $('select').append('<option>' + date.toLocaleDateString('en-US', {
    month: 'long'
  }) + '</option>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select></select>