jQuery - 显示当月的所有日期(以数字表示)

时间:2017-12-21 06:40:05

标签: jquery

如何在一个月内显示所有日期@格式

  

当月的所有日期: 1,2,3,4,5,6,7,8,9,10 ...... 31

HTML

<div id="allDates"></div>

的jQuery

$(document).ready(function(){
    var d = new Date();
    var allDates = d.getDate();
    $('#allDates').html('All days in current month:' + '<br>' + allDates);
});

4 个答案:

答案 0 :(得分:3)

使用日期构造函数生成一个月的第一个日期和月的最后一个日期,然后按下数组中的所有日期并显示它。

$(document).ready(function(){
    var today = new Date(),
    firstDay = new Date(today.getFullYear(), today.getMonth(), 1),
    lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0),
    result = [];

    while(firstDay <= lastDay){
      result.push(firstDay.getDate());
      firstDay.setDate(firstDay.getDate() + 1);
    }

    $('#allDates').html('All days in current month:' + '<br>' + result.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="allDates"></div>

使用此stackoverflow solution

function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

$(document).ready(function(){
    var today = new Date(),
    days = daysInMonth(today.getMonth() + 1, today.getFullYear()),
    result = Array.from({length:days}, (_,i) => i+1).join(',');
    $('#allDates').html('All days in current month:' + '<br>' + result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="allDates"></div>

答案 1 :(得分:2)

&#13;
&#13;
var d = new Date();
var LastDay = 32 - new Date(d.getFullYear(), d.getMonth(), 32).getDate();
var Output = "";
for (var i = 0; i < LastDay - 1; i++) {
    Output += (i + 1) + ", ";
}
document.write(Output);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用此

$(document).ready(function(){
  var d = new Date();
    var numberOfDays = getDaysInMonth(d.getMonth() + 1, d.getFullYear())
    var allDates = ''
  for (var i = 1; i <= numberOfDays; i++) {
    allDates += i + ' '
  }

  $('#allDates').html('All days in current month:' + '<br>' + allDates);
});
function getDaysInMonth(month,year) {
  return new Date(year, month, 0).getDate();
}

答案 3 :(得分:0)

这是另一个转折,获取该月的最后一天,然后循环以获得输出

var getDaysInMonth = function(month,year) {
  // Here January is 1 based
  //Day 0 is the last day in the previous month
 return new Date(year, month, 0).getDate();
// Here January is 0 based
// return new Date(year, month+1, 0).getDate();
};

$(document).ready(function(){
  var d = new Date();
    var lastdayOfmonth = getDaysInMonth(d.getMonth() , d.getFullYear())
    var allDates = ''
  for (var i = 1; i <= lastdayOfmonth; i++) {
    allDates += i + ' '
  }

  $('#allDates').html('Current month dates :' + '<br>' + allDates);
});

请参阅此链接: - https://www.w3resource.com/javascript-exercises/javascript-date-exercise-3.php