Angularjs date filter does not format json value

I have a service that returns json like this:

"Results":[{"Id":"1","SomeDate":"2/19/2013 10:34:04 PM"} 

When I try to format using the binding, it does not work - it just displays the line above:

 {{values.SomeDate| date:'mediumTime' }} 

However, it works if I just pass in this format:

 {{ '1997-03-01T00:00:00+01:00' | date:'mediumTime'}} 

What is the best way to fix this?

+8
angularjs
source share
3 answers

As mentioned in the comments of charlietfl, a clean option would be to update the service to return a date format that is already compatible with angular's built-in filters.

However, if this is not possible, you can configure your own filter to analyze your dates.

A (very small) library that I recommend is Moment.js: http://momentjs.com/

The following is an example blog post on how to wrap Moment.js in a custom angular filter: http://www.34m0.com/2012/07/angularjs-user-friendly-date-display.html

 angular.module('myModule'). filter('fromNow', function() { return function(dateString) { return moment(new Date(dateString)).fromNow() }; }); 

It will be used as:

 {{ reply.createdDate | fromNow }} 
+12
source share

You can put this in your controller:

  $scope.toJsDate = function(str){ if(!str)return null; return new Date(str); } 

and then:

 {{toJsDate(values.SomeDate)| date:'mediumTime' }} 
+9
source share

I would add a @AlexOsborn suggestion to use moment.js to create a custom filter, because moment.js can parse a string containing a date. In my filter implementation, I also delegate date formatting at the .js moment, because I feel that the date.js date formatting function is more complete than angular.js':

 angular .module("YourModuleNameHere") .filter("formatdate", [function () { var result = function (date, formatstring) { if(formatstring === null) { formatstring = "DD MMM YYYY"; } return moment(date).format(formatstring); } return result; }]); 

And you use it the same way you used the angular.js date filter (but to format the date you would use the .js moment formatting codes):

 <p>Today is {{moment() | formatdate}}</p> <p>Another date: {{values.SomeDate | formatdate:"ddd D MMM YYYY"}}</p> 
0
source share

All Articles