0

Issue


I am passing a JSON string back from my Web Service and for some reason it is returning /Date(1461106800000+0100)/.

I went the date to be returned in the format "yyyy-MM-dd"

I have been searching online and in my controller I have created a filter which looks like this:

app.filter("dateFilter", function () {
return function (item) {
    if (item != null) {
        return new Date(parseInt(item.substr(6)));
    }
    return "";
};
});

In my controller I have written this:

var bens = $filter('dateFilter')(ben.GetAllEventsByUserResult.HOLIDAY_START);

That returns this:

enter image description here

Conclusion


How can I get the date in the yyyy-MM-dd format?

Ben Clarke
  • 949
  • 3
  • 17
  • 39
  • You can look this answer : http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date, when you do new Date(), it's not formated yet ! – Damien Fayol Feb 16 '16 at 17:48
  • Have you read the API about date filters for Angular? https://docs.angularjs.org/api/ng/filter/date – Adjit Feb 16 '16 at 17:49
  • send valid ISO date strings or timestamps from server and you wouldn't need your custom filter and can use built in `date` filter – charlietfl Feb 16 '16 at 18:19

1 Answers1

1

try something like this, this uses the built in angular date filter with the newly parsed date.

app.filter("dateFilter", function ($filter) {
return function (item) {
    if (item != null) {
        var parsedDate = new Date(parseInt(item.substr(6)));
        return $filter('date')(parsedDate, 'yyyy-MM-dd');
    }
    return "";
};
});

Edit: I'd actually recommend, instead of having to use your custom filter all the time, you can add a HTTP interceptor, that reads your response, and automatically parses the dates, navigating the whole object using recursion. Then, throughout the rest of the application, you can use the built in filters as and when.

M21B8
  • 1,837
  • 8
  • 18
  • you could even move the format into a variable to be passed in, so you could parse into whatever date format you want. – M21B8 Feb 16 '16 at 17:52