【问题标题】:Getting all the dates of a month when a date is provided using angularjs使用angularjs提供日期时获取一个月的所有日期
【发布时间】:2019-05-21 00:41:37
【问题描述】:

当用户提供日期时,我想获取一个月的所有日期。我是 angularjs 的新手。我怎样才能做到这一点?

【问题讨论】:

标签: angularjs date


【解决方案1】:

实现这一目标的步骤...

  1. 将日期作为用户输入;
  2. 计算该月的第一个和最后一个日期;
  3. 运行一个循环,获取其间的所有日期并存储在一个数组中;
  4. 在屏幕上打印数组

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  $scope.particularDate;
  $scope.relevantMonth;
  $scope.relevantYear;
  $scope.relevantFirstDate;
  $scope.relevantLastDate;


  $scope.calcDate = function() {
    if ($scope.selectedDate) {
      $scope.yearPart = $scope.selectedDate.toString().substring(11, 15);
      $scope.particularDate = new Date($scope.selectedDate.toString().substring(0, 10));
      $scope.particularDate.setYear($scope.yearPart);

      $scope.relevantMonth = $scope.particularDate.getMonth() + 1;
      $scope.relevantYear = $scope.particularDate.getFullYear();

      $scope.relevantLastDate = new Date($scope.relevantYear, $scope.relevantMonth, 0);
      $scope.relevantFirstDate = new Date($scope.relevantYear, $scope.relevantMonth - 1, 1);
      $scope.fillAllDays();
    }
  }

  $scope.fillAllDays = function() {
    $scope.monthArray = [];

    var t = $scope.relevantFirstDate;
    $scope.monthArray.push(t.toLocaleDateString());

    for (var i = $scope.relevantFirstDate.getDate(); i < $scope.relevantLastDate.getDate(); i++) {
      t.setDate(t.getDate() + 1);
      $scope.monthArray.push(t.toLocaleDateString());
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  Date: <input type='date' ng-model='selectedDate' ng-change='calcDate()' /> <br>
  <hr/>
  <p ng-repeat='x in monthArray'>{{x}}</p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2012-05-29
    • 1970-01-01
    相关资源
    最近更新 更多