8

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?

1
  • 1
    docs define date formats, pass a valid format from server or create custom filter that parses your data to a valid date docs.angularjs.org/api/ng.filter:date Commented Feb 21, 2013 at 0:17

3 Answers 3

12

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 }}
Sign up to request clarification or add additional context in comments.

Comments

9

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' }}

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.