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?
The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.
AngularJS date filter is used to convert a date into a specified format. When the date format is not specified, the default date format is 'MMM d, yyyy'. Parameter Values: The date filter contains format and timezone parameters which is optional.
Explanation: AngularJS needs data in JSON format to populate its model.
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' }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With