Angular JS Date filter not working

devo picture devo · Oct 29, 2013 · Viewed 44.4k times · Source

I have an ng-repeat element which will loop through $http.get() result.

<tr ng-repeat="blog in posts">
     <td style="text-align:center">{{ $index+1 }}</td>
     <td>{{ blog.title }}</td>
     <td>
         {{ blog.author.name }}
     </td>
     <td>
         {{ blog.created_at | date:'MMM-dd-yyyy' }}
     </td>
</tr>

I have created_at as timestamp in MySQL database table. And I am using angular.js v1.0.7.

I am getting the same output from db table and date filter is not working. How can I solve this?

My ajax call,

$http({method: 'GET', url: 'http://localhost/app/blogs'}).
success(function(data, status, headers, config) {
    $scope.posts = data.posts;
}).
error(function(data, status, headers, config) {
    $scope.posts = [];
});

Answer

Anoopsingh Bayes picture Anoopsingh Bayes · Oct 29, 2013

The date passed to the filter needs to be of type javascript Date.

Have you checked what the value blog.created_at is displayed as without the filter?

You said your backed service is returning a string representing the date. You can resolve this in two ways:

  1. Make your server-side code return a json date object
    • check how the server side code serialize the json that it returns
  2. Write your own filter which accepts the string date and returns date in the required format
    • Note: you can call the angular filter in your own filter

You can write your own filter as follows:

app.filter('myDateFormat', function myDateFormat($filter){
  return function(text){
    var  tempdate= new Date(text.replace(/-/g,"/"));
    return $filter('date')(tempdate, "MMM-dd-yyyy");
  }
});

And use it like this in your template:

<td>
  {{ blog.created_at | myDateFormat }}
</td>

Rather than looping through the returned array and then applying the filter