I have a service that returns json like so:
"Results":[{"Id":"1","SomeDate":"2/19/2013 10:34:04 PM"}
When i try to format using binding, it doesnt work - it just displays the string 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?
As mentioned in the comments by charlietfl, a clean option would be to update the service to return a date format already compatible with the built-in angular filters.
However, if this is not possible, you could set up a custom filter to parse 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()
};
});
This would be used like:
{{ reply.createdDate | fromNow }}
You can place this in your controller:
$scope.toJsDate = function(str){
if(!str)return null;
return new Date(str);
}
and then:
{{toJsDate(values.SomeDate)| date:'mediumTime' }}
I would second @AlexOsborn's suggestion to use moment.js to create a custom filter because moment.js can parse the string containing the date. In my implementation of the filter, I also delegate date formatting to moment.js because I feel moment.js' date formatting feature is more comprehensive 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 just like you'd use angular.js date filter (but to format the date you'd use moment.js formatting codes):
<p>Today is {{moment() | formatdate}}</p>
<p>Another date: {{values.SomeDate | formatdate:"ddd D MMM YYYY"}}</p>