我正在array
中使用json
数据。在每一行中,我都有一个datetime
字段。每个datetime
字段都表示此形式的数据2016-11-19 00:00:00
。
我想将日期和月份分开显示为单独的值。
这是我的代码:
<span class="day">8</span>
<span class="month">{{ event.event_date | date:'MMM' }}</span>
<span class="year">2014</span>
<span class="time">12:00 AM</span>
我有一个简单的解决方案:
在控制器中:
$scope.myDate = new Date("2016-11-19 00:00:00");
$scope.myDate_month = $scope.myDate.getMonth();
$scope.myDate_day = $scope.myDate.getDate();
$scope.myDate_year = $scope.myDate.getFullYear();
$scope.time = $scope.myDate.getHours();
$scope.time = $scope.myDate.getMinutes();
在 html 中:
<span class="day">{{myDate_day}}</span>
<span class="month">{{myDate_month}}</span>
<span class="year">{{myDate_year}}</span>
<span class="time">{{myDate | date: 'h:mm a'}}</span>
由于您的日期是strings
的,您应该将它们解析为 Date,如下所示:
$scope.event_date = new Date("2016-11-19 00:00:00");
然后,您可以在视图中调用筛选器:
<span ng-bind="date | date:'MMM'"></span>
例:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.events = [];
// Simulation of $http.get
for (var i = 1; i < 10; i++) {
$scope.events.push({
"id": Math.floor(Math.random() * 100) + 1,
"event_date": "201" + i + "-0" + i + "-" + i + " 0" + i + ":00:00"
})
}
// Parsing your strings to date objects
$scope.events.map(function(value) {
value.event_date = new Date(value.event_date);
})
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div ng-repeat="event in events track by $index">
<!--
<span class="day">8</span>
<span class="month" ng-bind="event.event_date | date:'MMM'"></span>
<span class="year">2014</span>
<span class="time">12:00 AM</span>
-->
<span class="day" ng-bind="event.event_date | date:'dd'"></span>
<span class="month" ng-bind="event.event_date | date:'MMM'"></span>
<span class="year" ng-bind="event.event_date | date:'yyyy'"></span>
<span class="time" ng-bind="event.event_date | date:'HH:mm'"></span>
</div>
</body>
</html>
检查日期筛选器的 API。