OrderBy Date values, which are just strings in Angular JS

user3350593 picture user3350593 · Aug 14, 2014 · Viewed 14k times · Source

I'm trying to order some data by date, although the dates are just strings, in the format dd-mm-yyyy.

I made a filter which converted the plain string of numbers (which where in the US date format, where I wanted the UK date format) e.g 01272012 to 27-01-2014, but when I try to order them it still only sees them as numeric strings, so 01-01-1990 would come before 02-01-2014.

Any suggestions of how to do this in a filter?

Thanks!

Update

I figured out the dates would automatically get orderedif the date format was yyyy-mm-dd. I then used used orderBy:['date'] to order the data, only using my original filter when displaying the data.

I ended up having to reverse my data, showing the most recent dates. To achieve this I added a - to my orderBy statment: orderBy:['-date'].

Answer

David Bohunek picture David Bohunek · Aug 14, 2014

Because orderBy filter, you can use that. Your ng-repear would probably look similar to this:

ng-repeat="item in items | orderBy: orderByDate"

and then on your controller you would define the orderByDate function:

$scope.orderByDate = function(item) {
    var parts = item.dateString.split('-');
    var date = new Date(parseInt(parts[2], 
                        parseInt(parts[1]), 
                        parseInt(parts[0]));

    return date;
};

Implementation of the function is up to you. I choose to create Date from the string. The object you return from orderByDate function is then used to be order with using <, =, > operators.

EDIT: solution for :reverse

Since :reverse can't be used with a function passed as parameter, you can implement your custom function to return reversed value itself. In such case using Date is not possible, I would construct a number then and returned it with minus:

$scope.orderByDate = function(item) {
    var parts = item.dateString.split('-');
    var number = parseInt(parts[2] + parts[1] + parts[0]);

    return -number;
};