角度js:角度ng-repeat中的分割日期和时间参数

时间:2016-05-31 05:15:23

标签: javascript html angularjs

我在ng-repeat显示一些数据,我希望将日期显示为三个参数

1.Date 2个月 3.时间

我会将日期作为单个字符串2016-05-13 16:08:33

<div class="list-expense-menu-item" ng-repeat="notification in notifications">
  <h2>{{notification.text}}</h2>
  <span>Date:{{notification.notif_date}}</span>
</div>

预期

<span>Month:05</span>
<span>Date:16</span>
<span>Time:16:08</span>

如何将单个日期拆分为三个参数??

2 个答案:

答案 0 :(得分:3)

最好的方法是在显示通知数据之前对其进行转换。您可以使用正则表达式,或者只解析日期,然后使用日期方法。

&#13;
&#13;
angular.module('app', []);

angular
  .module('app')
  .controller('Example', function ($scope) {
    const inputData = [
      {text: 'some text', notif_date: '2016-05-13 16:08:33'},
      {text: 'some text', notif_date: '2017-06-13 18:28:33'}
    ];
  
    $scope.notifications = inputData.map(({text, notif_date}) => {
      const regexp = /^\d{4}-(\d{1,2})-(\d{1,2})\s*([\d:]*)$/;
      const matched = notif_date.match(regexp);
      
      return {
        text,
        month: matched[1],
        date: matched[2],
        time: matched[3]
      };
    });
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Example">
<div class="list-expense-menu-item" ng-repeat="notification in notifications">
  <h2>{{notification.text}}</h2>
  <span>Month:{{notification.month}}</span>
  <span>Date:{{notification.date}}</span>
  <span>Time:{{notification.time}}</span>
</div>
</div>
&#13;
&#13;
&#13;

使用Date的示例,cos您的字符串可以通过新的Date()轻松解析。

&#13;
&#13;
angular.module('app', []);

angular
  .module('app')
  .controller('Example', function ($scope) {
    const inputData = [
      {text: 'some text', notif_date: '2016-05-13 16:08:33'},
      {text: 'some text', notif_date: '2017-06-13 18:28:33'}
    ];
  
    $scope.notifications = inputData.map(({text, notif_date}) => {
      const date = new Date(notif_date);
      
      return {
        text,
        month: date.getMonth() + 1, //+1 because in JS months are numbered 0 - 11, so January is 0 and so on 
        date: date.getDate(),
        time: date.getHours() + ':' + date.getMinutes()
      };
    });
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Example">
<div class="list-expense-menu-item" ng-repeat="notification in notifications">
  <h2>{{notification.text}}</h2>
  <span>Month:{{notification.month}}</span>
  <span>Date:{{notification.date}}</span>
  <span>Time:{{notification.time}}</span>
</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在您的控制器中,像这样修改notif_date。

 notifications.forEach(function(notification){
   notification.notif_date = new Date(notification.notif_date);
 })

并在视图中尝试角度约会filter

  <span>Month:{{notification.notif_date | date:'MM'}}</span>
  <span>Date:{{notification.notif_date | date:'dd'}}</span>
  <span>Year:{{notification.notif_date | date:'yyyy'}}</span>