Nishara Kavindi
Nishara Kavindi

Reputation: 59

Format date in AngularJS is not working

In my project the data is coming to front-end as a json object as shown below:

{
  id: 1,
  meetingName: "Meeting 1",
  meetingDate: "2018-02-21",
  startTime: "10:00:00"
}

<td>{{meeting.startTime|date:"h:mma"}}</td>

I used the above method to format the date in angularjs code as 10:00 AM. But the start time is still shown as 10:00:00. Why is it not formatting the date according to the format?

Upvotes: 1

Views: 202

Answers (2)

lin
lin

Reputation: 18402

Filter date expects an object of type date. This custom filter could help you:

View

<div ng-controller="MyCtrl">
  {{data.startTime|timeFilter: data.meetingDate: 'h:mma'}}
  {{data.startTime|timeFilter: data.meetingDate: 'yyyy-MM-dd HH:mm:ss Z'}}
</div>

AngularJS application

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  $scope.data = {
    id: 1,
    meetingName: "Meeting 1",
    meetingDate: "2018-02-21",
    startTime: "10:00:00"
  };
});

myApp.filter('timeFilter', function ($filter) {
  return function (data, aDate, dateFilter) {
    return $filter('date')(new Date(aDate + " " + data), dateFilter);
  }
})

> Demo fiddle

Upvotes: 0

Manish
Manish

Reputation: 5066

date filter expects a date object as input. But you are passing a string. Below is a sample code that show the date as expected.

var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
  let info = {
    id: 1,
    meetingName: "Meeting 1",
    meetingDate: "2018-02-21",
    startTime: "10:00:00"
  }
  $scope.meetingDate= new Date(info.meetingDate + " " + info.startTime);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

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

    <p>Meeting Time= {{ meetingDate | date:"h:mma" }}</p>

  </div>

</body>

Date Filter Docs

Hope this helps :)

Upvotes: 2

Related Questions