如何以json格式存储日期,并在给定范围内逐个显示

How to store dates in json format and display them one by one for a given range?

本文关键字:范围内 显示 json 格式 日期 存储      更新时间:2023-09-26

我是angularjs的新手,我正在尝试以json格式存储日期,并以列表方式显示。

这里,我希望minDate是用户给出的日期,maxDate是当前日期。

我想通过"for"循环显示从minDate到maxDate的日期,其中日期递增1,我们是否也需要一个函数来计算天数?


HTML

<div ng-app='myApp' ng-controller="Main">
        <input type="date" ng-model="min">
        <li ng-repeat="n in range(min,max)">{{dt.date | date}}</li>
        </div>

控制器

myApp.controller('Main', function ($scope){
  $scope.max = new Date();
  $scope.date = [];
  $scope.range = function(min, max){ 
    for (var i = min; i <= max; i ++) {
    date.setDate(date.getDate() + i);
        $scope.date.push({
        dt: $scope.date
         });
return date;              
}
};

输出应类似

Date 1:
07/20/2016
Date 2:
07/24/2016
Day difference = n
Day 1=20 July.2016
Day 2=21 July.2016
Day 3=22 July.2016
Day 4=23 July.2016
Day 5=24 July.2016

我不会在ng repeat中使用函数,因为它将在每个摘要循环中调用。相反,只在您的最小日期更改时调用该函数。下面是它的样子:

控制器

myApp.controller('Main', function($scope) {
  $scope.min = new Date();
  $scope.max = new Date();
  $scope.dateRange = [];
  $scope.getDateRange = function() {
    $scope.dateRange = [{
      dt: angular.copy($scope.min)
    }];
    for (var thisDate = $scope.min; thisDate < $scope.max;) {
      thisDate.setDate(thisDate.getDate() + 1);
      $scope.dateRange.push({
        dt: angular.copy(thisDate)
      });
    }
  };
});

HTML

<div ng-controller="Main">
  <input type="date" ng-model="min" ng-change="getDateRange()">
  <li ng-repeat="d in dateRange">{{ d.dt | date}}</li>
</div>

你可以在这里看到它的工作