使用AngularJs在月中转换日期时间

时间:2016-07-12 04:44:45

标签: angularjs datetime

我在json中消费了array个数据。在每一行中,我都有一个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>

2 个答案:

答案 0 :(得分:0)

由于您的日期为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>

检查date-filter API

答案 1 :(得分:0)

我有一个简单的解决方案:

在控制器中:

$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>