user818700
user818700

Reputation:

AngularJS date filter not producing results

Currently I have the following binding in my view:

<p>{{claim.date}}</p>

Which contains something like this:

Oct 19, 2015 4:34:00 PM

I want to format it so that it displays like this:

Oct 19, 2015

Looking at all the AngularJS date filters I see that I need to do this:

<p>{{claim.date | date : 'mediumDate'}}</p>

However nothing is happening. Am I doing this right?

Upvotes: 2

Views: 126

Answers (2)

IggY
IggY

Reputation: 3135

var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
  $scope.date = "Oct 19, 2015 4:34:00 PM";
  $scope.date2 = new Date("Oct 19, 2015 4:34:00 PM");
});

app.filter('stringToDate', function() {
  return function(input) {
    return new Date(input);
  };
});

app.filter('stringToDateFormat', function($filter) { 
  return function(input, format) { 
    return $filter("date")(new Date(input), format);
  }; 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="App" ng-controller="Ctrl">
  <div>
    {{date | stringToDate |date: "mediumDate"}}
  </div>
    <div>
    {{date | stringToDateFormat: "mediumDate"}}
  </div>
  <div>
    {{date2 | date: "mediumDate"}}
  </div>

</body>

Upvotes: 2

Sarjan Desai
Sarjan Desai

Reputation: 3733

Check below snippet. It working fine for date object. Make sure that your object is date object, not string.

angular.module('myApp', []).controller('MyCtrl', function($scope) {
  $scope.date = new Date();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <p>{{date}}</p>
  <p>{{date | date : 'mediumDate'}}</p>
</div>

Upvotes: 1

Related Questions