Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs date filter not formatting my json value

Tags:

angularjs

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?

like image 897
schmoopy Avatar asked Feb 21 '13 00:02

schmoopy


People also ask

Which AngularJS filter formats an object to a JSON string?

The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.

What does the AngularJS filter date do?

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.

Does AngularJS need data to be in JSON format to populate its model?

Explanation: AngularJS needs data in JSON format to populate its model.


2 Answers

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 }}
like image 129
Alex Osborn Avatar answered Oct 17 '22 00:10

Alex Osborn


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' }}
like image 24
user1941747 Avatar answered Oct 17 '22 02:10

user1941747