如何使用Javascript AngularJS打印一个月的所有日期

How to print all the dates of a month using Javascript AngularJS

本文关键字:一个 日期 Javascript 何使用 AngularJS 打印      更新时间:2023-09-26

我想显示给定月份的所有日期。假设,如果我选择Oct, 2015,那么它应该在一个列表中显示该月的所有日期。我可以使用setDate()打印接下来365天的所有日期,但是我怎么能只打印选定月份的日期呢?检查此代码以显示接下来的365天。

function Ctrl($scope) {
  $scope.dates = [];
  for (i = 0; i <= 364; i++) {
    var d = new Date();
    $scope.dates.push(d.setDate(d.getDate() + i));
  }
}

可以使用DateJs

,你的代码可以像这样

function Ctrl($scope) {
  $scope.dates = [];
  for (i = 0; i < 365; i++) {
    $scope.dates.push((i).days().fromNow());
  }
}

如果你能得到一个月的总天数,那么你就可以做

 $scope.month =10; $scope.year =2015;  $scope.nDays = new Date( $scope.year,  $scope.month, 0).getDate() ;

以上代码得到2015年10月的n天。

用以下代码循环nDays

for (i = 1; i <= $scope.nDays; i++) {
var d = new Date();
$scope.dates.push(d.setDate(d.getDate() + i));}

希望能有所帮助。

注入moment js库,它将为您提供很多帮助

链接http://momentjs.com/

你很接近了。正如Jaromanda X建议的那样,从1开始,一直到月份变化(不要忘记将变量保持在本地)。您需要每次复制日期:

function Ctrl($scope) {
  $scope.dates = [];
  var d = new Date(),
      i = 1,
      m = d.getMonth();
  // Set date to start of month
  d.setDate(i);
  // Store the current month and keep going until it changes
  while (d.getMonth() == m) {
    // Store dates as a string (format however you wish)
    $scope.dates.push('' + d);
    // Or store dates as Date objects
    $scope.dates.push(new Date(+d));
    // Increment date
    d.setDate(++i);
  }
  // return something?
}

编辑

允许输入月份(也是do而不是for循环的例子):

// Use calendar month number for month, i.e. 1=jan, 2=feb, etc.
function Ctrl($scope, month) {
  $scope.dates = [];
  var d = new Date();
  d.setMonth(month - 1, 1);
  do {
    $scope.dates.push('' + d);
    d.setDate(d.getDate() + 1);
  } while (d.getDate() != 1)
}

或者允许输入月份和年份,默认为当前月份和年份:

function Ctrl($scope, month, year) {
  $scope.dates = [];
  var d = new Date();
  d.setFullYear(+year || d.getFullYear(), month - 1 || d.getMonth(), 1);
  do {
    $scope.dates.push('' + d);
    d.setDate(d.getDate() + 1);
  } while (d.getDate() != 1)
}

您可以这样尝试:

function Ctrl($scope) {
  $scope.dates = [];
  var month = 3;
  var year = 2015;
  for (i = 1; i <= 30; i++) { //You have to know the number of days in the month you want tho
    var d = new Date();
    $scope.dates.push(new Date(year, month, i));
  }
}