【问题标题】:How to print all the dates of a month using Javascript AngularJS如何使用 Javascript AngularJS 打印一个月的所有日期
【发布时间】:2016-01-17 12:54:15
【问题描述】:

我想显示给定月份的所有日期。假设,如果我选择 2015 年 10 月,那么它应该在列表中显示该月的所有日期。我可以使用 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));
  }
}

【问题讨论】:

  • 看看momentjs.com。您可能会找到答案。
  • .setDate(1),循环直到 getMonth() 改变,或者 getDate() 再次为 1,你的选择

标签: javascript html angularjs date


【解决方案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));
  }
}

【讨论】:

  • 您可以使用new Date(year, month, 0).getDate()获取一个月的天数
【解决方案2】:

您可以使用DateJs

你的代码可能是这样的

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

【讨论】:

  • 我不想使用任何第三方库。
  • 为什么?使用其他人以前做过的东西是一个很好的做法
【解决方案3】:

如果你能得到一年中一个月的总天数,那么你就可以完成

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

以上代码获取 2015 年 10 月的 nDays。

使用以下代码循环 nDays

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

希望对你有帮助。

【讨论】:

【解决方案4】:

你很亲密。正如 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)
}

【讨论】:

【解决方案5】:

注入 moment js 库,它会为此提供很多帮助

这是链接 http://momentjs.com/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2021-06-11
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多