Angularjs:如何过滤日期

时间:2017-02-17 05:51:33

标签: angularjs angular-filters

我想将其格式化为日期格式,如

  

DD-MM-YYYY

从API获取的数据如下

 Mon Feb 13 2017 12:30:28 GMT+0000 (UTC)

任何帮助?

1 个答案:

答案 0 :(得分:0)

您可以在Viewcontroller

中进行转换

1)在视图中格式化日期:

<p>Date Formatted in view = {{ today | date:"dd-MM-y" }}</p>

{{ today | date:"dd-MM-y" }}是角度的默认日期过滤器。

2)在控制器中格式化日期:

$scope.date = $filter('date')($scope.today, "dd-MM-yyyy");,您需要注入角度为$filter的模块。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="datCtrl">

<p>Date Formatted in view = {{ today | date:"dd-MM-y" }}</p>

<p>Date Formatted in Controller = {{date}}</p>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope,$filter) {
    $scope.today = new Date();
    $scope.date = $filter('date')($scope.today, "dd-MM-yyyy"); 
});
</script>

<p>The date filter formats a date object to a readable format.</p>

</body>
</html>

请跑上面的SNIPPET

Here is a working DEMO