OrderBy Date values โ€‹โ€‹that are just strings in Angular JS

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

I created a filter that converted a simple string of numbers (where in the date format in the USA, where I need the date format in the UK), for example 01272012 - 01/27/2014, but when I try to order them, it sees them as number strings, so 01-01-1990 will run until 02-01-2014.

Any suggestions on how to do this in the filter?

Thanks!

Update

I realized that dates would be automatically ordered if the date format was yyyy-mm-dd. Then I used orderBy:['date'] to organize the data, using only my original filter when displaying the data.

I had to turn over my data, indicating the latest dates. To achieve this, I added - to my order. Element: orderBy:['-date'] .

+6
source share
2 answers

Since the filter is orderBy , you can use this. Your ng-repear probably looks something like this:

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

and then on the controller you 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; }; 

The implementation of the function is up to you. I choose to create a Date from a string. The object that you return from the orderByDate function is then used for order using the <, =,> operators.

EDIT: solution for :reverse

Since :reverse cannot be used with the function passed as a parameter, you can implement your custom function to return the opposite value. In this case, using Date impossible, I would then build a number and return it with a minus:

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

var now = Date.now (); now = $ filter ('date') (now, 'yyyy-MM-ddThh: mm: ss + hh: mm');

Then you can filter the data with the corresponding formatted date.

0
source

Source: https://habr.com/ru/post/973814/


All Articles